• 15 апреля стартует «Курс «SQL-injection Master» ©» от команды The Codeby

    За 3 месяца вы пройдете путь от начальных навыков работы с SQL-запросами к базам данных до продвинутых техник. Научитесь находить уязвимости связанные с базами данных, и внедрять произвольный SQL-код в уязвимые приложения.

    На последнюю неделю приходится экзамен, где нужно будет показать свои навыки, взломав ряд уязвимых учебных сайтов, и добыть флаги. Успешно сдавшие экзамен получат сертификат.

    Запись на курс до 25 апреля. Получить промодоступ ...

ProgressBar

  • Автор темы nor
  • Дата начала
N

nor

Всем привет.

Столкнулся со следующей проблемой. Как и многие другие девелоперы, пользуюсь API функциями из nnotesws.dll для отображения прогресс бар. Все замечательно работает для Lotus Notes под Win. Но, естественно, такой dll нет в директории клиента под Linux. Там прогресс бар мой не работает и вызывает ошибку "Error in loading DLL", что также совершенно логично.

Вообщем, если кто строил прогресс бар для linux станций, помогите, пожалуйста.
 
K

Kee_Keekkenen

если не лотусовый вариант, то может java вариант использовать ?
 
K

Kee_Keekkenen

пример использования java через LS2J
можешь по аналогии, добавить класс ProgressBar в свой агент и осуществить в нужно месте его вызов и передачу параметров для обновления ползунка в прогрессбаре:
Java:
import java.awt.*;
import java.awt.event.*;
 
class ProgressBar {
public final int BOXMSG_NONE = 0; // display nothing in the progress bar
public final int BOXMSG_PERCENT = 1; // display the percent complete (like "20%")
public final int BOXMSG_NUMBERS = 2; // display the number complete (like "4 of 10")
Frame parent;
Dialog pbar;
Label mess;
ProgressBox pbox;
Button cancel;
long curVal, maxVal;
boolean shouldCancel;
/*
* When you create a new instance of a ProgressBar, it sets up the progress bar and
* immediately displays it. The message parameter is a label that displays just above
* the progress bar, the maxValue parameter indicates what value should be considered
* 100% on the progress bar, and the allowCancel parameter indicates whether or not
* a Cancel button should be displayed at the bottom of the dialog.
*/
public ProgressBar(String message, long maxValue, boolean allowCancel) {
shouldCancel = false;
// this is the invisible Frame we'll be using to call all the Dialog
parent = new Frame();
pbar = new Dialog(parent, "Agent Progress Bar");
// add the message to the top of the dialog
Panel top = new Panel(new FlowLayout(FlowLayout.CENTER, 1, 1));
mess = new Label(message);
top.add(mess);
pbar.add("North", top);
// add the progress bar to the middle of the dialog
Panel middle = new Panel(new FlowLayout(FlowLayout.CENTER, 1, 1));
pbox = new ProgressBox(maxValue);
middle.add(pbox);
pbar.add("Center", middle);
// add the Cancel button to the bottom of the dialog (if allowCancel is true)
if (allowCancel) {
Panel bottom = new Panel(new FlowLayout(FlowLayout.CENTER, 1, 1));
cancel = new Button("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//pbar.dispose();
shouldCancel = true;
}
});
bottom.add(cancel);
pbar.add("South", bottom);
}
// display the ProgressBar dialog
Dimension d = pbar.getToolkit().getScreenSize();
pbar.setLocation(d.width / 3, d.height / 3); // center the ProgressBar (sort of)
pbar.pack(); // organize all its components
pbar.setResizable(false); // make sure the user can't resize it
pbar.toFront(); // give the ProgressBar focus
pbar.show(); // and display it
}
/*
* The updateValue method allows you to update the value used by the progress bar
* in order to calculate the percent complete on the bar. Percent complete is the value
* parameter passed to this method divided by the maxValue you passed in when you
* initially instantiated the ProgressBar.
*/
public void updateValue(long value) {
pbox.updateValue(value);
}
/*
* The updateMaxValue method allows you to update the maximum value used by the
* progress bar in order to calculate the percent complete on the bar.
*/
public void updateMaxValue(long value) {
pbox.updateMaxValue(value);
}
/*
* The getCurrentValue method returns the current value used by the progress bar
* to determine the percent complete.
*/
public long getCurrentValue() {
return pbox.getCurrentValue();
}
/*
* The getMaxValue method returns the maximum value used by the progress bar
* to determine the percent complete (once the current value equals the maximum
* value, we're at 100%)
*/
public long getMaxValue() {
return pbox.getMaxValue();
}
/*
* The setBarText method sets the value of the dispText field in the progress bar,
* which indicates what kind of message should be displayed in the bar. You'll
* normally use a value of BOXMSG_NONE, BOXMSG_PERCENT, or
* BOXMSG_NUMBERS for this value.
*/
public void setBarText(int boxMsgValue) {
pbox.setBarMsg(boxMsgValue);
}
/*
* The dispose method removes the ProgressBar from the screen display.
*/
public void dispose() {
// use this when you're ready to clean up
try {
pbar.dispose();
} catch (Exception e) {}
try {
parent.dispose();
} catch (Exception e) {}
}
/*
* The isCancelClicked method indicates whether or not the user clicked the
* Cancel button. Normally, when you realize that the user has clicked Cancel,
* you'll want to call the dispose method to stop displaying the ProgressBar.
*/
public boolean isCancelClicked() {
return shouldCancel;
}
/*
* The ProgressBox is the actual awt component that displays a progress bar.
* It's implemented here as an inner class of the ProgressBar class, but it can
* be a separate class too. Just make sure you import java.awt.*
*
* Julian Robichaux -- http://www.nsftools.com
*/
class ProgressBox extends Canvas {
public final int MSG_NONE = 0; // display nothing in the progress bar
public final int MSG_PERCENT = 1; // display the percent complete (like "20%")
public final int MSG_NUMBERS = 2; // display the number complete (like "4 of 10")
private long maxVal, currentVal;
private int cols, width, height, dispText;
private Color barClr, borderClr, textClr;
public ProgressBox(long maxValue) {
this(maxValue, 40);
}
public ProgressBox(long maxValue, int width) {
// one unit of width for this component is the width of
// the letter 'X' in the current font (so a width of 10 is
// a width of 'XXXXXXXXXX' using the current font)
maxVal = maxValue;
currentVal = 0;
cols = width;
dispText = MSG_PERCENT;
barClr = new Color(50, 200, 255); // make the progress bar light blue
borderClr = Color.gray; // make the bar border gray
textClr = Color.darkGray; // make the text dark gray
}
protected void measure() {
// get the global values we use in relation to our current font
FontMetrics fm = this.getFontMetrics(this.getFont());
if (fm == null)
return;
width = fm.stringWidth("X") * cols;
height = fm.getHeight() + 4;
}
public void addNotify() {
// automatically invoked after our Canvas is created but
// before it's displayed (FontMetrics aren't available until
// super.addNotify() has been called)
super.addNotify();
measure();
}
public Dimension getPreferredSize() {
// called by the LayoutManager to find out how big we want to be
return new Dimension(width + 4, height + 4);
}
public Dimension getMinimumSize() {
// called by the LayoutManager to find out what our bare minimum
// size requirements are
return getPreferredSize();
}
public void updateValue(long value) {
// change the currentVal, which is used to determine what our percent
// complete is, and update the progress bar
currentVal = value;
this.repaint();
}
public void updateMaxValue(long value) {
// change the maxVal, which is used to determine what our percent
// complete is ((currentVal / maxVal) * 100 = percent complete),
// and update the progress bar
maxVal = value;
this.repaint();
}
public long getCurrentValue() {
// return the currentVal
return currentVal;
}
public long getMaxValue() {
// return the maxVal
return maxVal;
}
public void setBarMsg(int msgValue) {
// change the dispText value, which is used to determine what text,
// if any, is displayed in the progress bar (use either MSG_NONE,
// MSG_PERCENT, or MSG_NUMBERS)
dispText = msgValue;
}
public void setColors(Color barColor, Color borderColor, Color textColor) {
// set the colors used by the progress bar components
if (barColor != null) barClr = barColor;
if (borderColor != null) borderClr = borderColor;
if (textColor != null) textClr = textColor;
}
public void paint(Graphics g) {
// draw the actual progress bar to the screen
// this is the bar itself
g.setColor(barClr);
g.fillRect(0, 0, (int)((currentVal * width) / maxVal), height);
// this is the border around the bar
g.setColor(borderClr);
g.drawRect(0, 0, width, height);
// this is the text to display (if any)
g.setColor(textClr);
if (dispText == MSG_PERCENT)
centerText(String.valueOf((int)((currentVal * 100) / maxVal)) + "%", g, width, height);
else if (dispText == MSG_NUMBERS)
centerText("(" + currentVal + " of " + maxVal + ")", g, width, height);
}
private void centerText(String s, Graphics g, int w, int h) {
// from the centerText method in "Java Examples in a Nutshell"
FontMetrics fm = this.getFontMetrics(this.getFont());
if (fm == null)
return;
int sWidth = fm.stringWidth(s);
int sx = (w - sWidth) / 2;
int sy = (h - fm.getHeight()) / 2 + fm.getAscent();
g.drawString(s, sx, sy);
}
} // end of the ProgressBox class
} // end of the ProgressBar class
Код:
Option Public
Option Explicit
Uselsx "*javacon"
Use "JavaProgressBar"
Class LS2JProgBar
Private jSession As JavaSession
Private jError As JavaError
Private pbClass As JavaClass
Private pb As JavaObject
Public Sub New (msg As String, maxVal As Long, allowCancel As Boolean)
'** create a new progress bar, with the given message text, max value,
'** and an optional Cancel button
Set jSession = New JavaSession
Set pbClass = jSession.GetClass("ProgressBar")
Set pb = pbClass.CreateObject("(Ljava/lang/String;JZ)V", msg, maxVal, allowCancel)
End Sub
Public Sub Delete ()
'** make sure we get rid of the progress bar when we're done
If Not (pb Is Nothing) Then
pb.dispose
End If
End Sub
Public Property Get BOXMSG_NONE As Integer
'** constant value for ProgressBar.setBarText()
'** display nothing in the progress bar
BOXMSG_NONE = pb.BOXMSG_NONE
End Property
Public Property Get BOXMSG_PERCENT As Integer
'** constant value for ProgressBar.setBarText()
'** display the percent complete (like "20%")
BOXMSG_PERCENT = pb.BOXMSG_PERCENT
End Property
Public Property Get BOXMSG_NUMBERS As Integer
'** constant value for ProgressBar.setBarText()
'** display the number complete (like "4 of 10")
BOXMSG_NUMBERS = pb.BOXMSG_NUMBERS
End Property
Public Sub setBarText (barType As Integer)
'** set the type of text we should see in the progress bar, based on
'** the BOXMSG properties above
pb.setBarText(barType)
End Sub
Public Sub updateValue (count As Long)
'** tell the progress bar what our current value is, and make it redraw
pb.updateValue(count)
End Sub
Public Function getCurrentValue () As Long
'** get the current value of the progress bar (which is the last thing you
'** passed to the updateValue method)
getCurrentValue = pb.getCurrentValue()
End Function
Public Sub updateMaxValue (maxVal As Long)
'** tell the progress bar what our maximum value is, and make it redraw
pb.updateMaxValue(maxVal)
End Sub
Public Function getMaxValue () As Long
'** get the maximum value of the progress bar (which is the last thing you
'** passed to the updateMaxValue method, or the maxVal parameter you
'** used when you created the progress bar)
getMaxValue = pb.getMaxValue()
End Function
Public Function isCancelClicked () As Boolean
'** returns True if the user clicked the cancel button on the progress bar
'** dialog, False otherwise
isCancelClicked = pb.isCancelClicked()
End Function
Public Function getLastError () As String
'** get any Java errors that occurred, and clear the Java error stack
Set jError = jSession.getLastJavaError()
getLastError = jError.errorMsg
jSession.ClearJavaError
End Function
End Class
Sub Initialize
On Error Goto processError
Dim session As New NotesSession
Dim db As NotesDatabase
Dim dc As NotesDocumentCollection
Dim doc As NotesDocument
Dim totalDocs As Long
Dim count As Integer

'** as an example, we'll just step through all the documents in the local
'** Bookmark.nsf file
Set db = session.GetDatabase("", "Bookmark.nsf")
Set dc = db.AllDocuments
totalDocs = dc.Count

'** create a new progress bar
Dim pb As New LS2JProgBar("Checking " & totalDocs & " docs in " & db.FileName, totalDocs, True)
pb.setBarText(pb.BOXMSG_PERCENT)

'** start stepping through the documents
Set doc = dc.GetFirstDocument
Do Until (doc Is Nothing)
'** if the user clicked the Cancel button we should stop
If (pb.isCancelClicked()) Then
Print "User clicked cancel. Stopping after " & count & " of " & totalDocs & " docs"
Exit Do
End If
count = count + 1
If (count Mod 10 = 0) Then
pb.updateValue(count)
End If
Sleep(0.01)
Set doc = dc.GetNextDocument(doc)
Loop

'** when we're done with the progress bar, we should explicitly Delete it
'** so everything gets cleaned up in the backend
Delete pb
'** and we're done
Exit Sub

processError:
'** report any errors we get and keep on going
Dim pbError As String
If Not (pb Is Nothing) Then
pbError = pb.getLastError
End If
If (pbError = "") Then
Print "Notes Error at line " & Erl & ": " & Error$
Else
Print Err,Error,Erl, Getthreadinfo(1)
End If
Resume Next
End Sub
 
N

nor

Для: Kee_Keekkenen


А ты год приведенный тестировал????!!!!

У моего Lotus Notes от этого кода расстройство желудка случилось. :( :) :)
 
K

Kee_Keekkenen

не судите строго.. код не мой.. он работает через пень колоду.. вообще-то он работает, но в нем есть ошибки логики.. а предлагался он только в качестве идеи.. пока не было потребности в такой мульке, но думаю попозже тоже посмотрю что там есть хорошего и переделаю по человечески, чтоб например при генерациии отчетов бежал ползунок...
 
A

Akupaka

прогрессбар (нашел на нсфтулз), ну... сразу глюк вылез ведомый - тыцнул в окно клиента - вернуться к окошку диалога фонарь...
но, в общем, попытаться можно
не уверен, что на счет прозрачности окошка - не мастер я в яве ;)
Java:
/*
* This is an example of how to use a ProgressBar in a Java agent in Lotus Notes.
*
* The ProgressBar class below uses the java.awt classes for windowing. java.awt
* should already be included with the Java classes that ship with Notes, so you
* don't have to include anything special (like the Java Swing classes) with any
* agents that you use this class with. Example usage is in the NotesMain() method.
*
* Julian Robichaux -- http://www.nsftools.com
*/
import lotus.domino.*;
import java.awt.*;
import java.awt.event.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
// (Your code goes here)
int maxVal = 11;
ProgressBar pb = new ProgressBar("This is a test bar", maxVal);
for (int i = 0; i <= maxVal; i++) {
// if the user clicked the Cancel button, exit the loop
if (pb.isCancelClicked())
break;
// for the sake of example, cycle through the different ProgressBar text displays
pb.setBarText(i % 3);
// update the amount of work we've done
pb.updateValue(i);
// wait a second
Thread.sleep(1000);
}
pb.dispose();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* The ProgressBar class allows you to create non-modal progress bars
* using only the java.awt classes. All you have to do is create an instance
* of a ProgressBar, update the progress using the updateValue method as
* you're doing work, and use the dispose method to close the ProgressBar
* dialog when you're done. The ProgressBar also includes an optional
* Cancel button, so the user can cancel the action while your process is
* running (if you use this button, make sure you check the isCancelClicked
* method occassionally to see if the user clicked Cancel).
*
* This class has been implemented here as an inner class, but there's
* no reason why it couldn't be a class all by itself. The progress bar
* component itself is actually an inner class to this inner class. Read
* the comments there to see how it works.
*
* Make sure you import java.awt.* and java.awt.event.*
*
* Julian Robichaux -- http://www.nsftools.com
*/
class ProgressBar {
public final int BOXMSG_NONE = 0; // display nothing in the progress bar
public final int BOXMSG_PERCENT = 1; // display the percent complete (like "20%")
public final int BOXMSG_NUMBERS = 2; // display the number complete (like "4 of 10")
Frame parent;
Dialog pbar;
Label mess;
ProgressBox pbox;
Button cancel;
long curVal, maxVal;
boolean shouldCancel;
/*
* This version of the constructor creates a ProgressBar that includes a Cancel button
*/
public ProgressBar(String message, long maxValue) {
this(message, maxValue, true);
}
/*
* When you create a new instance of a ProgressBar, it sets up the progress bar and
* immediately displays it. The message parameter is a label that displays just above
* the progress bar, the maxValue parameter indicates what value should be considered
* 100% on the progress bar, and the allowCancel parameter indicates whether or not
* a Cancel button should be displayed at the bottom of the dialog.
*/
public ProgressBar(String message, long maxValue, boolean allowCancel) {
shouldCancel = false;
// this is the invisible Frame we'll be using to call all the Dialog
parent = new Frame();
pbar = new Dialog(parent, "Agent Progress Bar");
// add the message to the top of the dialog
Panel top = new Panel(new FlowLayout(FlowLayout.CENTER, 1, 1));
mess = new Label(message);
top.add(mess);
pbar.add("North", top);
// add the progress bar to the middle of the dialog
Panel middle = new Panel(new FlowLayout(FlowLayout.CENTER, 1, 1));
pbox = new ProgressBox(maxValue);
middle.add(pbox);
pbar.add("Center", middle);
// add the Cancel button to the bottom of the dialog (if allowCancel is true)
if (allowCancel) {
Panel bottom = new Panel(new FlowLayout(FlowLayout.CENTER, 1, 1));
cancel = new Button("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//pbar.dispose();
shouldCancel = true;
}
});
bottom.add(cancel);
pbar.add("South", bottom);
}
// display the ProgressBar dialog
Dimension d = pbar.getToolkit().getScreenSize();
pbar.setLocation(d.width / 3, d.height / 3); // center the ProgressBar (sort of)
pbar.pack(); // organize all its components
pbar.setResizable(false); // make sure the user can't resize it
pbar.toFront(); // give the ProgressBar focus
pbar.show(); // and display it
}
/*
* The updateValue method allows you to update the value used by the progress bar
* in order to calculate the percent complete on the bar. Percent complete is the value
* parameter passed to this method divided by the maxValue you passed in when you
* initially instantiated the ProgressBar.
*/
public void updateValue(long value) {
pbox.updateValue(value);
}
/*
* The updateMaxValue method allows you to update the maximum value used by the
* progress bar in order to calculate the percent complete on the bar.
*/
public void updateMaxValue(long value) {
pbox.updateMaxValue(value);
}
/*
* The getCurrentValue method returns the current value used by the progress bar
* to determine the percent complete.
*/
public long getCurrentValue() {
return pbox.getCurrentValue();
}
/*
* The getMaxValue method returns the maximum value used by the progress bar
* to determine the percent complete (once the current value equals the maximum
* value, we're at 100%)
*/
public long getMaxValue() {
return pbox.getMaxValue();
}
/*
* The setBarText method sets the value of the dispText field in the progress bar,
* which indicates what kind of message should be displayed in the bar. You'll
* normally use a value of BOXMSG_NONE, BOXMSG_PERCENT, or
* BOXMSG_NUMBERS for this value.
*/
public void setBarText(int boxMsgValue) {
pbox.setBarMsg(boxMsgValue);
}
/*
* The dispose method removes the ProgressBar from the screen display.
*/
public void dispose() {
// use this when you're ready to clean up
try {
pbar.dispose();
} catch (Exception e) {}
try {
parent.dispose();
} catch (Exception e) {}
}
/*
* The isCancelClicked method indicates whether or not the user clicked the
* Cancel button. Normally, when you realize that the user has clicked Cancel,
* you'll want to call the dispose method to stop displaying the ProgressBar.
*/
public boolean isCancelClicked() {
return shouldCancel;
}

/*
* The ProgressBox is the actual awt component that displays a progress bar.
* It's implemented here as an inner class of the ProgressBar class, but it can
* be a separate class too. Just make sure you import java.awt.*
*
* Julian Robichaux -- http://www.nsftools.com
*/
class ProgressBox extends Canvas {
public final int MSG_NONE = 0; // display nothing in the progress bar
public final int MSG_PERCENT = 1; // display the percent complete (like "20%")
public final int MSG_NUMBERS = 2; // display the number complete (like "4 of 10")
private long maxVal, currentVal;
private int cols, width, height, dispText;
private Color barClr, borderClr, textClr;
public ProgressBox(long maxValue) {
this(maxValue, 40);
}
public ProgressBox(long maxValue, int width) {
// one unit of width for this component is the width of
// the letter 'X' in the current font (so a width of 10 is
// a width of 'XXXXXXXXXX' using the current font)
maxVal = maxValue;
currentVal = 0;
cols = width;
dispText = MSG_PERCENT;
barClr = new Color(50, 200, 255); // make the progress bar light blue
borderClr = Color.gray; // make the bar border gray
textClr = Color.darkGray; // make the text dark gray
}
protected void measure() {
// get the global values we use in relation to our current font
FontMetrics fm = this.getFontMetrics(this.getFont());
if (fm == null)
return;
width = fm.stringWidth("X") * cols;
height = fm.getHeight() + 4;
}
public void addNotify() {
// automatically invoked after our Canvas is created but
// before it's displayed (FontMetrics aren't available until
// super.addNotify() has been called)
super.addNotify();
measure();
}
public Dimension getPreferredSize() {
// called by the LayoutManager to find out how big we want to be
return new Dimension(width + 4, height + 4);
}
public Dimension getMinimumSize() {
// called by the LayoutManager to find out what our bare minimum
// size requirements are
return getPreferredSize();
}
public void updateValue(long value) {
// change the currentVal, which is used to determine what our percent
// complete is, and update the progress bar
currentVal = value;
this.repaint();
}
public void updateMaxValue(long value) {
// change the maxVal, which is used to determine what our percent
// complete is ((currentVal / maxVal) * 100 = percent complete),
// and update the progress bar
maxVal = value;
this.repaint();
}
public long getCurrentValue() {
// return the currentVal
return currentVal;
}
public long getMaxValue() {
// return the maxVal
return maxVal;
}
public void setBarMsg(int msgValue) {
// change the dispText value, which is used to determine what text,
// if any, is displayed in the progress bar (use either MSG_NONE,
// MSG_PERCENT, or MSG_NUMBERS)
dispText = msgValue;
}
public void setColors(Color barColor, Color borderColor, Color textColor) {
// set the colors used by the progress bar components
if (barColor != null) barClr = barColor;
if (borderColor != null) borderClr = borderColor;
if (textColor != null) textClr = textColor;
}
public void paint(Graphics g) {
// draw the actual progress bar to the screen
// this is the bar itself
g.setColor(barClr);
g.fillRect(0, 0, (int)((currentVal * width) / maxVal), height);
// this is the border around the bar
g.setColor(borderClr);
g.drawRect(0, 0, width, height);
// this is the text to display (if any)
g.setColor(textClr);
if (dispText == MSG_PERCENT)
centerText(String.valueOf((int)((currentVal * 100) / maxVal)) + "%", g, width, height);
else if (dispText == MSG_NUMBERS)
centerText("(" + currentVal + " of " + maxVal + ")", g, width, height);
}
private void centerText(String s, Graphics g, int w, int h) {
// from the centerText method in "Java Examples in a Nutshell"
FontMetrics fm = this.getFontMetrics(this.getFont());
if (fm == null)
return;
int sWidth = fm.stringWidth(s);
int sx = (w - sWidth) / 2;
int sy = (h - fm.getHeight()) / 2 + fm.getAscent();
g.drawString(s, sx, sy);
}
} // end of the ProgressBox class
} // end of the ProgressBar class
}
 
A

Akupaka

малость переделал:
показывает окно с сообщением и кнопкой "отмена", можно и без
остается только его разместить и доделать способ появления/исчезновения чтобы красиво
и фиксированный размер чтоб был... пока используется стандартный способ размещения компонент...
Java:
import lotus.domino.*;
import java.awt.*;
import java.awt.event.*;
 
public class JavaAgent extends AgentBase {
   public void NotesMain() {
	  try {
		 Session session = getSession();
		 AgentContext agentContext = session.getAgentContext();
 
		 // (Your code goes here)
		 int maxVal = 3;
		 PopupMessage ppm = new PopupMessage("This is a test bar");
 
		 for (int i = 0; i <= maxVal; i++) {
			// if the user clicked the Cancel button, exit the loop
			if (ppm.isCancelClicked())
			   break;
			Thread.sleep(1000);
		 }
		 ppm.dispose();
	  } catch (Exception e) {
		 e.printStackTrace();
	  }
   }
 
   class PopupMessage {
	  Frame parent;
	  Dialog pbar;
	  Label mess;
	  Button cancel;
	  long curVal, maxVal;
	  boolean shouldCancel;
 
	  /*
	  * This version of the constructor creates a ProgressBar that includes a Cancel button
	  */
	  public PopupMessage(String message) {
		 this(message, true);
	  }
 
	  public PopupMessage(String message, boolean allowCancel) {
		 shouldCancel = false;
		 // this is the invisible Frame we'll be using to call all the Dialog
		 parent = new Frame();
		 pbar = new Dialog(parent, "Agent Progress Bar");
 
		 // add the message to the top of the dialog
		 Panel top = new Panel(new FlowLayout(FlowLayout.CENTER, 1, 1));
		 mess = new Label(message);
		 top.add(mess);
		 pbar.add("North", top);
 
		 // add the Cancel button to the bottom of the dialog (if allowCancel is true)
		 if (allowCancel) {
			Panel bottom = new Panel(new FlowLayout(FlowLayout.CENTER, 1, 1));
			cancel = new Button("Cancel");
			cancel.addActionListener(new ActionListener() {
			   public void actionPerformed(ActionEvent e) {
				  //pbar.dispose();
				  shouldCancel = true;
			   }
			});
			bottom.add(cancel);
			pbar.add("South", bottom);
		 }
 
		 // display the ProgressBar dialog
		 Dimension d = pbar.getToolkit().getScreenSize();
		 pbar.setLocation(d.width / 3, d.height / 3); // center the ProgressBar (sort of)
		 pbar.pack(); // organize all its components
		 pbar.setResizable(false); // make sure the user can't resize it
		 pbar.toFront(); // give the ProgressBar focus
		 pbar.show(); // and display it
 
	  }
 
	  public void dispose() {
		 // use this when you're ready to clean up
		 try {
			pbar.dispose();
		 } catch (Exception e) {}
		 try {
			parent.dispose();
		 } catch (Exception e) {}
	  }
 
	  public boolean isCancelClicked() {
		 return shouldCancel;
	  }
   } // end of the PopupMessage class
}
 

VladSh

начинающий
Lotus Team
11.12.2009
1 783
157
BIT
55
Изменил:
- добавил возможность работы с AlwaysOnTop: если при AlwaysOnTop=true клацнуть мимо диалога, то диалог будет продолжать отображаться, если false, то скроется;
- при нажатии Cancel диалог скрывается сразу; вызывающий код будет работать дальше, если в нём не ставить проверку на pb.isCancelClicked(), что, собственно, чаще всего и случается;
- отдельный метод вывода диалога для случаев множественного использования прогрессбара (несколько различных обработок документов) в одном коде;
- методы для установки свойств (как душе угодно).
Java:
import java.awt.Button;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
 
/*
* The ProgressBar class allows you to create non-modal progress bars
* using only the java.awt classes. All you have to do is create an instance
* of a ProgressBar, update the progress using the updateValue method as
* you're doing work, and use the dispose method to close the ProgressBar
* dialog when you're done. The ProgressBar also includes an optional
* Cancel button, so the user can cancel the action while your process is
* running (if you use this button, make sure you check the isCancelClicked
* method occassionally to see if the user clicked Cancel).
*
* This class has been implemented here as an inner class, but there's
* no reason why it couldn't be a class all by itself. The progress bar
* component itself is actually an inner class to this inner class. Read
* the comments there to see how it works.
*
* Make sure you import java.awt.* and java.awt.event.*
*
* Julian Robichaux -- http://www.nsftools.com
*/
public class ProgressBar {
   public final int BOXMSG_NONE = 0;	  // display nothing in the progress bar
   public final int BOXMSG_PERCENT = 1;   // display the percent complete (like "20%")
   public final int BOXMSG_NUMBERS = 2;   // display the number complete (like "4 of 10")
   Frame parent;
   Dialog pbar;
   Label mess;
   ProgressBox pbox;
   Button cancel;
   boolean allowAlwaysOnTop = false;
   boolean allowCancel = true;
   long curVal, maxVal;
   boolean shouldCancel;
 
   public ProgressBar() {
   }
   public ProgressBar(boolean bAllowAlwaysOnTop) {
	  allowAlwaysOnTop = bAllowAlwaysOnTop;
   }
 
   public void setAllowAlwaysOnTop(boolean value) {
	  allowAlwaysOnTop = value;
   }
   public void setAllowCancel(boolean value) {
	  allowCancel = value;
   }
 
   /**
   * Display dialog
   * @param message - is a label that displays just above the progress bar
   * @param maxValue - indicates what value should be considered 100% on the progress bar
   */
   public void show(String message, long maxValue) {
	  show(message, maxValue, allowCancel);
   }
 
   /**
   * Display dialog ext
   * @param bAllowCancel - indicates whether or not a Cancel button should be displayed at the bottom of the dialog
   */
   public void show(String message, long maxValue, boolean bAllowCancel) {
	  allowCancel = bAllowCancel;
	  shouldCancel = false;
	  // this is the invisible Frame we'll be using to call all the Dialog
	  parent = new Frame();
	  pbar = new Dialog(parent, "Agent Progress Bar");
 
	  if (allowAlwaysOnTop) {
		 try {
			  // may not have enough rights in java.policy
			pbar.setAlwaysOnTop(allowAlwaysOnTop);
		 } catch (Exception e) {
			System.out.println(e.getLocalizedMessage());
		 }
	  }
 
	  pbar.addWindowFocusListener(new WindowFocusListener() {
		 public void windowLostFocus(WindowEvent arg0) {
			if (!pbar.isAlwaysOnTop()) {
			   dispose();
			}
		 }
		 public void windowGainedFocus(WindowEvent arg0) {
		 }
	  });
 
	  // add the message to the top of the dialog
	  Panel top = new Panel(new FlowLayout(FlowLayout.CENTER, 1, 1));
	  mess = new Label(message);
	  top.add(mess);
	  pbar.add("North", top);
 
	  // add the progress bar to the middle of the dialog
	  Panel middle = new Panel(new FlowLayout(FlowLayout.CENTER, 1, 1));
	  pbox = new ProgressBox(maxValue);
	  middle.add(pbox);
	  pbar.add("Center", middle);
 
	  // add the Cancel button to the bottom of the dialog (if allowCancel is true)
	  if (allowCancel) {
		 Panel bottom = new Panel(new FlowLayout(FlowLayout.CENTER, 1, 1));
		 cancel = new Button("Cancel");
		 cancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			   shouldCancel = true;
			   dispose();
			}
		 });
		 bottom.add(cancel);
		 pbar.add("South", bottom);
	  }
 
	  // display the ProgressBar dialog
	  Dimension d = pbar.getToolkit().getScreenSize();
	  pbar.setLocation(d.width / 3, d.height / 3);	 // center the ProgressBar (sort of)
	  pbar.pack();			 // organize all its components
	  pbar.setResizable(false);	 // make sure the user can't resize it
	  pbar.toFront();		   // give the ProgressBar focus
	  pbar.show();		   // and display it
   }
 
   /**
   * The updateValue method allows you to update the value used by the progress bar
   * in order to calculate the percent complete on the bar. Percent complete is the value
   * parameter passed to this method divided by the maxValue you passed in when you
   * initially instantiated the ProgressBar.
   */
   public void updateValue(long value) {
	  pbox.updateValue(value);
   }
 
   /**
   * The updateMaxValue method allows you to update the maximum value used by the
   * progress bar in order to calculate the percent complete on the bar.
   */
   public void updateMaxValue(long value) {
	  pbox.updateMaxValue(value);
   }
 
   /**
   * The getCurrentValue method returns the current value used by the progress bar
   * to determine the percent complete.
   */
   public long getCurrentValue() {
	  return pbox.getCurrentValue();
   }
 
   /**
   * The getMaxValue method returns the maximum value used by the progress bar
   * to determine the percent complete (once the current value equals the maximum
   * value, we're at 100%)
   */
   public long getMaxValue() {
	  return pbox.getMaxValue();
   }
 
   /**
   * The setBarText method sets the value of the dispText field in the progress bar,
   * which indicates what kind of message should be displayed in the bar. You'll
   * normally use a value of BOXMSG_NONE, BOXMSG_PERCENT, or
   * BOXMSG_NUMBERS for this value.
   */
   public void setBarText(int boxMsgValue) {
	  pbox.setBarMsg(boxMsgValue);
   }
 
   /**
   * The isCancelClicked method indicates whether or not the user clicked the
   * Cancel button. Normally, when you realize that the user has clicked Cancel,
   * you'll want to call the dispose method to stop displaying the ProgressBar.
   */
   public boolean isCancelClicked() {
	  return shouldCancel;
   }
 
   /**
   * The dispose method removes the ProgressBar from the screen display.
   */
   public void dispose() {
	  // use this when you're ready to clean up
	  try {
		 pbar.dispose();
	  } catch (Exception e) {}
	  try {
		 parent.dispose();
	  } catch (Exception e) {}
   }
 
   /**
   * The ProgressBox is the actual awt component that displays a progress bar.
   * It's implemented here as an inner class of the ProgressBar class, but it can
   * be a separate class too. Just make sure you import java.awt.*
   *
   * Julian Robichaux -- http://www.nsftools.com
   */
   class ProgressBox extends Canvas {
	  private static final long serialVersionUID = 1L;
	  public final int MSG_NONE = 0;		// display nothing in the progress bar
	  public final int MSG_PERCENT = 1;	 // display the percent complete (like "20%")
	  public final int MSG_NUMBERS = 2;	 // display the number complete (like "4 of 10")
	  private long maxVal, currentVal;
	  private int cols, width, height, dispText;
	  private Color barClr, borderClr, textClr;
 
	  public ProgressBox(long maxValue) {
		 this(maxValue, 40);
	  }
 
	  public ProgressBox(long maxValue, int width) {
		 // one unit of width for this component is the width of
		 // the letter 'X' in the current font (so a width of 10 is
		 // a width of 'XXXXXXXXXX' using the current font)
		 maxVal = maxValue;
		 currentVal = 0;
		 cols = width;
		 dispText = MSG_PERCENT;
		 barClr = new Color(50, 200, 255);  // make the progress bar light blue
		 borderClr = Color.gray;			// make the bar border gray
		 textClr = Color.darkGray;		  // make the text dark gray
	  }
 
	  protected void measure() {
		 // get the global values we use in relation to our current font
		 FontMetrics fm = this.getFontMetrics(this.getFont());
		 if (fm == null)
			return;
		 width = fm.stringWidth("X") * cols;
		 height = fm.getHeight() + 4;
	  }
 
	  public void addNotify() {
		 // automatically invoked after our Canvas is created but
		 // before it's displayed (FontMetrics aren't available until
		 // super.addNotify() has been called)
		 super.addNotify();
		 measure();
	  }
 
	  public Dimension getPreferredSize() {
		 // called by the LayoutManager to find out how big we want to be
		 return new Dimension(width + 4, height + 4);
	  }
 
	  public Dimension getMinimumSize() {
		 // called by the LayoutManager to find out what our bare minimum
		 // size requirements are
		 return getPreferredSize();
	  }
 
	  public void updateValue(long value) {
		 // change the currentVal, which is used to determine what our percent
		 // complete is, and update the progress bar
		 currentVal = value;
		 this.repaint();
	  }
 
	  public void updateMaxValue(long value) {
		 // change the maxVal, which is used to determine what our percent
		 // complete is ((currentVal / maxVal) * 100 = percent complete),
		 // and update the progress bar
		 maxVal = value;
		 this.repaint();
	  }
 
	  public long getCurrentValue() {
		 // return the currentVal
		 return currentVal;
	  }
 
	  public long getMaxValue() {
		 // return the maxVal
		 return maxVal;
	  }
 
	  public void setBarMsg(int msgValue) {
		 // change the dispText value, which is used to determine what text,
		 // if any, is displayed in the progress bar (use either MSG_NONE,
		 // MSG_PERCENT, or MSG_NUMBERS)
		 dispText = msgValue;
	  }
 
	  public void setColors(Color barColor, Color borderColor, Color textColor) {
		 // set the colors used by the progress bar components
		 if (barColor != null) barClr = barColor;
		 if (borderColor != null) borderClr = borderColor;
		 if (textColor != null) textClr = textColor;
	  }
 
	  public void paint(Graphics g) {
		 // draw the actual progress bar to the screen
		 // this is the bar itself
		 g.setColor(barClr);
		 g.fillRect(0, 0, (int)((currentVal * width) / maxVal), height);
 
		 // this is the border around the bar
		 g.setColor(borderClr);
		 g.drawRect(0, 0, width, height);
 
		 // this is the text to display (if any)
		 g.setColor(textClr);
		 if (dispText == MSG_PERCENT)
			centerText(String.valueOf((int)((currentVal * 100) / maxVal)) + "%", g, width, height);
		 else if (dispText == MSG_NUMBERS)
			centerText("(" + currentVal + " of " + maxVal + ")", g, width, height);
	  }
 
	  private void centerText(String s, Graphics g, int w, int h) {
		 // from the centerText method in "Java Examples in a Nutshell"
		 FontMetrics fm = this.getFontMetrics(this.getFont());
		 if (fm == null)
			return;
		 int sWidth = fm.stringWidth(s);
		 int sx = (w - sWidth) / 2;
		 int sy = (h - fm.getHeight()) / 2 + fm.getAscent();
		 g.drawString(s, sx, sy);
	  }
   }	// end of the ProgressBox class
}	// end of the ProgressBar class
Java:
import lotus.domino.*;
 
public class JavaAgent extends AgentBase {
   public void NotesMain() {
	  try {
		 int maxVal = 11;
		 ProgressBar pb = new ProgressBar(true);
		 pb.show("This is a test bar", maxVal);
		 
		 for (int i = 0; i <= maxVal; i++) {
			
			// (Your code goes here)
			
			pb.updateValue(i);
			
			// if the user clicked the Cancel button, exit the loop
			//	if (pb.isCancelClicked())
			//	   break;
			
			System.out.println(i);
			
			// wait a second; in production code, this should not be
			Thread.sleep(200);
		 }
		 pb.dispose();
		 
	  } catch (Exception e) {
		 e.printStackTrace();
	  }
   }
}
Хотелось бы ещё, для полного счастья, сделать "бегунок" в стиле Win7.. ну или хотя бы такой же зелёненький.
 
A

alexas

Совсем простой ProgressBar
 

Вложения

  • ProgrBar.zip
    25,3 КБ · Просмотры: 228
A

alexas

И как этим пользоваться?
Все просто:
1 открывается DialogBox
2 в его контексте запускается контролируемый скрипт, который дополнительно к полезной работе пишет значения прогресс бара и выполненных процентов (в примере - поля Pr и Pers соответственно) в DialogBox
3 контролируемый скрипт находится в кнопке, которую в onLoad нажимает JS через setinterval (в этом вся фишка - если запускать скрипты по-другому, то сначала они выполнятся, а только потом будет виден сам ДиалогБокс
Все :)

тут пример
 

Вложения

  • ProgrBar.zip
    39,1 КБ · Просмотры: 228

savl

Lotus Team
28.10.2011
2 597
310
BIT
177
Коллеги, у меня с недавнего времени стала выпадать ошибка:
LS2J Error: Java constructor failed to execute
Как раз с ProgressBar от Julian Robichaux -- , код которого VladSh выложил выше.
Но я брал именно готовую версию без модификаций.
Так вот, ошибка чисто на моей машине.
У коллег все работает, даже если я перекомпилю - у них все работает.
Ошибок в компиляции нет.
Что можно сделать?
Текущий клиент: Release 9.0.1FP2 SHF255 + JVM Patсh
Клиент переставляли, не предлагать.
У коллег другой, но когда ставил - проверял работу. Ни чисты, ни только с FP, ни полный - не работает...
Компилили под разные версии 1,4/1,5/1,6 - не работает.
Есть внешняя JRE: jre1.8.0_20
И JDK: jdk1.8.0
Переменной JAVA_HOME - нет.
Повторяю ошибка только у меня.
 

garrick

Lotus Team
26.10.2009
1 349
151
BIT
176
Попробуй вместо notes.exe запустить nlnotes.exe и проверить как работает.
 

garrick

Lotus Team
26.10.2009
1 349
151
BIT
176
Я просто подумал, что Designer запускает JVM с какими-то хитрыми ключами, ан нет... В Java Debug Console или Log чего-нибудь пишет?
 

savl

Lotus Team
28.10.2011
2 597
310
BIT
177
garrick
Естественно нет.
Java писать не будет, потому что создать объект не удается.
В локальный Log нет ничего, вызов на клиенте.
 

garrick

Lotus Team
26.10.2009
1 349
151
BIT
176
И ещё... Клиенты одинаковой версии, в файлах jvm/lib/secutiry/java.policy различия есть?
 

garrick

Lotus Team
26.10.2009
1 349
151
BIT
176
Скачал посмотреть этот пример, у меня работает. Конфигурация Notes такая же. Я вот ещё подумал, если на 8-ке работает, а на 9-ке нет, то если посмотреть код LS 8-м дизайнером - он такой же? Судя по ошибке, проблема в вызове конструктора Java класса в LS, но если бы она реально была, то не работало бы везде.
 
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!