Applet Event Handler
Would someone please help me. I am new to applet development and I get a compile error associated with the event handling in my first ever applet code as follows:
C:\j2sdk1.4.2_01\bin>javac trajectory_j.java
trajectory_j.java:248: illegal start of expression
private class Handler implements ActionListener {
^
trajectory_j.java:248: ';' expected
private class Handler implements ActionListener {
^
2 errors
de.
This is the code:
// trajectory Analysis Program: trajectory_j.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class trajectory_j extends JApplet implements ActionListener {
private JTextArea introductionArea, resultsArea;
private JLabel spanLabel, chordLabel,
thicknessLabel, massLabel, altitudeLabel, velocityLabel,
trajectory_angleLabel, time_incrementLabel, rotation_factorLabel,
calculationLabel, resultsLabel;
private JTextField spanField, chordField, thicknessField,
massField, altitudeField, velocityField, trajectory_angleField,
time_incrementField, rotation_factorField;
private JButton startButton, resetButton, contButton, termButton;
String introduction_string, span_string, chord_string, thickness_string, mass_string,
altitude_string, velocity_string, trajectory_angle_string,
time_increment_string, rotation_factor_string, results_string;
double span, chord, thickness, mass, altitude, velocity, trajectory_angle, time_increment,
rotation_factor, distance, velocity_fps, elapsed_time;
int status_a;
int status_b;
int status_c;
/* deletion of code segment a
span = 0;
chord = 0;
thickness = 0;
mass = 0;
altitude = 0;
velocity = 0;
trajectory_angle = 0;
time_increment = 0;
rotation_factor = 0;
distance = 0;
velocity_fps = 0;
elapsed_time = 0;
velocity_fps = 0;
elapsed_time = 0;
// create objects
public void init()
status_a = 0;
status_b = 0;
status_c = 0;
// create container & panel
Container container = getContentPane();
Panel panel = new Panel( new FlowLayout( FlowLayout.LEFT));
container.add( panel );
// set up vertical boxlayout
Box box = Box.createVerticalBox();
Box inputbox1 = Box.createHorizontalBox();
Box inputbox2 = Box.createHorizontalBox();
Box inputbox3 = Box.createHorizontalBox();
Box buttonbox = Box.createHorizontalBox();
introduction_string = "This is the introduction";
// set up introduction
introductionArea = new JTextArea( introduction_string, 10, 50 );
introductionArea.setEditable( false );
box.add( new JScrollPane( introductionArea ) );
box.add( Box.createVerticalStrut (10) );
box.add( inputbox1);
// set up span
spanLabel = new JLabel( "span (feet)" );
spanField = new JTextField(5 );
inputbox1.add( spanLabel );
inputbox1.add( spanField );
Dimension minSize = new Dimension(5, 15);
Dimension prefSize = new Dimension(5, 15);
Dimension maxSize = new Dimension(Short.MAX_VALUE, 15);
inputbox1.add(new Box.Filler(minSize, prefSize, maxSize));
// set up chord
chordLabel = new JLabel( "chord (feet)" );
chordField = new JTextField(5 );
inputbox1.add( chordLabel );
inputbox1.add( chordField );
inputbox1.add(new Box.Filler(minSize, prefSize, maxSize));
// set up thickness
thicknessLabel = new JLabel( "thickness (feet)" );
thicknessField = new JTextField(5 );
inputbox1.add( thicknessLabel );
inputbox1.add( thicknessField );
inputbox1.add(new Box.Filler(minSize, prefSize, maxSize));
// set up mass
massLabel = new JLabel( "mass (slugs)" );
massField = new JTextField(5);
inputbox1.add( massLabel );
inputbox1.add( massField );
box.add( Box.createVerticalStrut (10) );
box.add( inputbox2);
// set up altitude
altitudeLabel = new JLabel( "altitude (feet)");
altitudeField = new JTextField(5 );
inputbox2.add( altitudeLabel );
inputbox2.add( altitudeField );
inputbox2.add(new Box.Filler(minSize, prefSize, maxSize));
// set up velocity
velocityLabel = new JLabel( "velocity (Mach Number)");
velocityField = new JTextField(5);
inputbox2.add( velocityLabel );
inputbox2.add( velocityField );
inputbox2.add(new Box.Filler(minSize, prefSize, maxSize));
// set up trajectory_angle
trajectory_angleLabel = new JLabel( "trajectory angle ( -90 degrees <= trajectory angle <= 90 degrees )");
trajectory_angleField = new JTextField(5);
inputbox2.add( trajectory_angleLabel );
inputbox2.add( trajectory_angleField );
box.add( Box.createVerticalStrut (10) );
box.add( inputbox3);
Dimension minSizeF = new Dimension(70, 15);
Dimension prefSizeF = new Dimension(70, 15);
Dimension maxSizeF = new Dimension(Short.MAX_VALUE, 15);
inputbox3.add(new Box.Filler(minSizeF, prefSizeF, maxSizeF));
// set up time_increment
time_incrementLabel = new JLabel( "time increment (seconds)" );
time_incrementField = new JTextField(5);
inputbox3.add( time_incrementLabel );
inputbox3.add( time_incrementField );
inputbox3.add(new Box.Filler(minSizeF, prefSizeF, maxSizeF));
// set up rotation_factor
rotation_factorLabel = new JLabel( "rotation factor ( non-negative number)" );
rotation_factorField = new JTextField(5);
inputbox3.add( rotation_factorLabel );
inputbox3.add( rotation_factorField );
inputbox3.add(new Box.Filler(minSizeF, prefSizeF, maxSizeF));
box.add( Box.createVerticalStrut (10) );
box.add( buttonbox);
// set up start
startButton = new JButton( "START" );
buttonbox.add( startButton );
Dimension minSizeB = new Dimension(10, 30);
Dimension prefSizeB = new Dimension(10, 30);
Dimension maxSizeB = new Dimension(Short.MAX_VALUE, 30);
buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
// set up reset
resetButton = new JButton( "RESET" );
buttonbox.add( resetButton );
buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
// set up cont
contButton = new JButton( "CONTINUE" );
buttonbox.add( contButton );
buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
// set up term
termButton = new JButton( "END" );
buttonbox.add( termButton );
box.add( Box.createVerticalStrut (10) );
// set up results
resultsArea = new JTextArea( results_string, 10, 50 );
resultsArea.setEditable( false );
box.add( new JScrollPane( resultsArea ) );
// add box to panel
panel.add( box );
// register event handlers
Handler handler = new Handler();
spanField.addActionListener( handler );
chordField.addActionListener( handler );
thicknessField.addActionListener( handler );
massField.addActionListener( handler );
altitudeField.addActionListener( handler );
velocityField.addActionListener( handler );
trajectory_angleField.addActionListener( handler );
time_incrementField.addActionListener( handler );
rotation_factorField.addActionListener( handler );
startButton.addActionListener( handler );
resetButton.addActionListener( handler );
contButton.addActionListener( handler );
termButton.addActionListener( handler );
// private inner class for event handling
private class Handler implements ActionListener {
// process handler events
public void actionPerformed( ActionEvent event )
// process resetButton event
if ( event.getSource() == resetButton )
reset();
// process contButton event
if ( event.getSource() == contButton )
cont();
// process endButton event
if ( event.getSource() == termButton )
// process span event
if( event.getSource() == spanField ) {
span = Double.parseDouble( event.getActionCommand() );
spanField.setText( span_string );
status_b++;
// process chord event
if( event.getSource() == spanField ) {
span = Double.parseDouble( event.getActionCommand() );
spanField.setText( chord_string );
status_b++;
// process thickness event
if( event.getSource() == thicknessField ) {
thickness = Double.parseDouble( event.getActionCommand() );
spanField.setText( thickness_string );
status_b++;
// process mass event
if( event.getSource() == massField ) {
mass = Double.parseDouble( event.getActionCommand() );
spanField.setText( mass_string );
status_b++;
// process altitude event
if( event.getSource() == altitudeField ) {
altitude = Double.parseDouble( event.getActionCommand() );
spanField.setText( altitude_string );
status_b++;
// process velocity event
if( event.getSource() == velocityField ) {
velocity = Double.parseDouble( event.getActionCommand() );
spanField.setText( velocity_string );
status_b++;
// process trajectory_angle event
if( event.getSource() == trajectory_angleField ) {
trajectory_angle = Double.parseDouble( event.getActionCommand() );
spanField.setText( trajectory_angle_string );
status_b++;
// process time_increment event
if( event.getSource() == time_incrementField ) {
time_increment = Double.parseDouble( event.getActionCommand() );
spanField.setText( time_increment_string );
status_b++;
// process rotation_factor event
if( event.getSource() == rotation_factorField ) {
rotation_factor = Double.parseDouble( event.getActionCommand() );
spanField.setText( rotation_factor_string );
status_b++;
// process startButton event
if ( event.getSource() == startButton && status_b == 9 ) {
status_c = 1;
} // end method event handler
} // end Handler class
} // end method init
public void strtb()
/* deletion of code segment 1
startButton.addActionListener(
new ActionListener() { // anonymous inner class
// set text in resultsArea
public void actionPerformed( ActionEvent event )
if( status_c == 1 ){
calculate();
results();
resultsArea.setText( results() );
/* deletion of code segment 2
}// end method actionPerformed1
} // end anonymous inner class1
); // end call to addActionlistener1
} // end method strtb
public void reset()
/* deletion of code segment 3
resetButton.addActionListener(
new ActionListener() { // anonymous inner class
// set text in resultsArea
public void actionPerformed( ActionEvent event )
span_string = "";
chord_string = "";
thickness_string = "";
mass_string = "";
altitude_string = "";
velocity_string = "";
trajectory_angle_string = "";
time_increment_string = "";
rotation_factor_string = "";
results_string = "";
spanField.setText( span_string );
chordField.setText( chord_string );
thicknessField.setText( thickness_string );
massField.setText( mass_string );
altitudeField.setText( altitude_string );
velocityField.setText( velocity_string );
trajectory_angleField.setText( trajectory_angle_string );
time_incrementField.setText( time_increment_string );
rotation_factorField.setText( rotation_factor_string );
resultsArea.setEditable( true );
resultsArea.setText( results_string );
resultsArea.setEditable( false );
span = 0;
chord = 0;
thickness = 0;
mass = 0;
altitude = 0;
velocity = 0;
trajectory_angle = 0;
time_increment = 0;
rotation_factor = 0;
distance = 0;
velocity_fps = 0;
elapsed_time = 0;
/* deletion of code segment 4
} // end method actionPerformed2
} // end anonymous inner class2
); // end call to addActionlistener2
} // end method reset
public void cont()
//later
public void calculate()
distance = 1;
altitude = 2;
trajectory_angle = 3;
velocity_fps = 4;
elapsed_time = 5;
public String results()
results_string =
"Distance =\t\t" + distance + " miles\n"
+ "Altitude =\t\t" + altitude + " feet\n"
+ "Trajectory Angle =\t" + trajectory_angle + " degrees\n"
+ "Velocity =\t\t" + velocity_fps + " feet per second\n"
+ "Elapsed Time =\t\t" + elapsed_time + " seconds\n"
+ "\nstatus_a = " + status_a + "\nstatus_b = "
+ status_b + "\nstatus_c = " + status_c;
return results_string;
public void start()
if(status_a == 0 )
strtb();
if (status_b == 0)
reset();
}// end method start
} //end class trajectory_a
The following are copies of html and java source code files for a prior runnable version ( trajectory_b ) of this program which can enlighten some functionality intended by the program.
(trajectory_b.html):
<html>
<appletcode = "trajectory_b.class" width = "800" height = "600">
</applet>
</html>
(trajectory_b.java):
// trajectory Analysis Program: trajectory_b.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class trajectory_b extends JApplet implements ActionListener {
private JTextArea introductionArea, resultsArea;
private JLabel spanLabel, chordLabel,
thicknessLabel, massLabel, altitudeLabel, velocityLabel,
trajectory_angleLabel, time_incrementLabel, rotation_factorLabel,
calculationLabel, resultsLabel;
private JTextField spanField, chordField, thicknessField,
massField, altitudeField, velocityField, trajectory_angleField,
time_incrementField, rotation_factorField;
private JButton startButton, resetButton, contButton, termButton;
String introduction_string, span_string, chord_string, thickness_string, mass_string,
altitude_string, velocity_string, trajectory_angle_string,
time_increment_string, rotation_factor_string, results_string;
double span, chord, thickness, mass, altitude, velocity, trajectory_angle, time_increment,
rotation_factor, distance, velocity_fps, elapsed_time;
int status_a;
int status_b;
int status_c;
/* deletion of code segment a
span = 0;
chord = 0;
thickness = 0;
mass = 0;
altitude = 0;
velocity = 0;
trajectory_angle = 0;
time_increment = 0;
rotation_factor = 0;
distance = 0;
velocity_fps = 0;
elapsed_time = 0;
velocity_fps = 0;
elapsed_time = 0;
// create objects
public void init()
status_a = 0;
status_b = 0;
status_c = 0;
// create container & panel
Container container = getContentPane();
Panel panel = new Panel( new FlowLayout( FlowLayout.LEFT));
container.add( panel );
// set up vertical boxlayout
Box box = Box.createVerticalBox();
Box inputbox1 = Box.createHorizontalBox();
Box inputbox2 = Box.createHorizontalBox();
Box inputbox3 = Box.createHorizontalBox();
Box buttonbox = Box.createHorizontalBox();
introduction_string = "This is the introduction";
// set up introduction
introductionArea = new JTextArea( introduction_string, 10, 50 );
introductionArea.setEditable( false );
box.add( new JScrollPane( introductionArea ) );
box.add( Box.createVerticalStrut (10) );
box.add( inputbox1);
// set up span
spanLabel = new JLabel( "span (feet)" );
spanField = new JTextField(5 );
inputbox1.add( spanLabel );
inputbox1.add( spanField );
Dimension minSize = new Dimension(5, 15);
Dimension prefSize = new Dimension(5, 15);
Dimension maxSize = new Dimension(Short.MAX_VALUE, 15);
inputbox1.add(new Box.Filler(minSize, prefSize, maxSize));
// set up chord
chordLabel = new JLabel( "chord (feet)" );
chordField = new JTextField(5 );
inputbox1.add( chordLabel );
inputbox1.add( chordField );
inputbox1.add(new Box.Filler(minSize, prefSize, maxSize));
// set up thickness
thicknessLabel = new JLabel( "thickness (feet)" );
thicknessField = new JTextField(5 );
inputbox1.add( thicknessLabel );
inputbox1.add( thicknessField );
inputbox1.add(new Box.Filler(minSize, prefSize, maxSize));
// set up mass
massLabel = new JLabel( "mass (slugs)" );
massField = new JTextField(5);
inputbox1.add( massLabel );
inputbox1.add( massField );
box.add( Box.createVerticalStrut (10) );
box.add( inputbox2);
// set up altitude
altitudeLabel = new JLabel( "altitude (feet)");
altitudeField = new JTextField(5 );
inputbox2.add( altitudeLabel );
inputbox2.add( altitudeField );
inputbox2.add(new Box.Filler(minSize, prefSize, maxSize));
// set up velocity
velocityLabel = new JLabel( "velocity (Mach Number)");
velocityField = new JTextField(5);
inputbox2.add( velocityLabel );
inputbox2.add( velocityField );
inputbox2.add(new Box.Filler(minSize, prefSize, maxSize));
// set up trajectory_angle
trajectory_angleLabel = new JLabel( "trajectory angle ( -90 degrees <= trajectory angle <= 90 degrees )");
trajectory_angleField = new JTextField(5);
inputbox2.add( trajectory_angleLabel );
inputbox2.add( trajectory_angleField );
box.add( Box.createVerticalStrut (10) );
box.add( inputbox3);
Dimension minSizeF = new Dimension(70, 15);
Dimension prefSizeF = new Dimension(70, 15);
Dimension maxSizeF = new Dimension(Short.MAX_VALUE, 15);
inputbox3.add(new Box.Filler(minSizeF, prefSizeF, maxSizeF));
// set up time_increment
time_incrementLabel = new JLabel( "time increment (seconds)" );
time_incrementField = new JTextField(5);
inputbox3.add( time_incrementLabel );
inputbox3.add( time_incrementField );
inputbox3.add(new Box.Filler(minSizeF, prefSizeF, maxSizeF));
// set up rotation_factor
rotation_factorLabel = new JLabel( "rotation factor ( non-negative number)" );
rotation_factorField = new JTextField(5);
inputbox3.add( rotation_factorLabel );
inputbox3.add( rotation_factorField );
inputbox3.add(new Box.Filler(minSizeF, prefSizeF, maxSizeF));
box.add( Box.createVerticalStrut (10) );
box.add( buttonbox);
// set up start
startButton = new JButton( "START" );
buttonbox.add( startButton );
Dimension minSizeB = new Dimension(10, 30);
Dimension prefSizeB = new Dimension(10, 30);
Dimension maxSizeB = new Dimension(Short.MAX_VALUE, 30);
buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
// set up reset
resetButton = new JButton( "RESET" );
buttonbox.add( resetButton );
buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
// set up cont
contButton = new JButton( "CONTINUE" );
buttonbox.add( contButton );
buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
// set up term
termButton = new JButton( "END" );
buttonbox.add( termButton );
box.add( Box.createVerticalStrut (10) );
// set up results
resultsArea = new JTextArea( results_string, 10, 50 );
resultsArea.setEditable( false );
box.add( new JScrollPane( resultsArea ) );
// add box to panel
panel.add( box );
// register event handlers
Handler handler = new Handler();
spanField.addActionListener( handler );
chordField.addActionListener( handler );
thicknessField.addActionListener( handler );
massField.addActionListener( handler );
altitudeField.addActionListener( handler );
velocityField.addActionListener( handler );
trajectory_angleField.addActionListener( handler );
time_incrementField.addActionListener( handler );
rotation_factorField.addActionListener( handler );
startButton.addActionListener( handler );
resetButton.addActionListener( handler );
contButton.addActionListener( handler );
termButton.addActionListener( handler );
} // end method init
// process handler events
public void actionPerformed( ActionEvent event )
// process resetButton event
if ( event.getSource() == resetButton )
reset();
// process contButton event
if ( event.getSource() == contButton )
cont();
// process endButton event
if ( event.getSource() == termButton )
// process span event
if( event.getSource() == spanField ) {
span = Double.parseDouble( event.getActionCommand() );
spanField.setText( span_string );
status_b++;
// process chord event
if( event.getSource() == spanField ) {
span = Double.parseDouble( event.getActionCommand() );
spanField.setText( chord_string );
status_b++;
// process thickness event
if( event.getSource() == thicknessField ) {
thickness = Double.parseDouble( event.getActionCommand() );
spanField.setText( thickness_string );
status_b++;
// process mass event
if( event.getSource() == massField ) {
mass = Double.parseDouble( event.getActionCommand() );
spanField.setText( mass_string );
status_b++;
// process altitude event
if( event.getSource() == altitudeField ) {
altitude = Double.parseDouble( event.getActionCommand() );
spanField.setText( altitude_string );
status_b++;
// process velocity event
if( event.getSource() == velocityField ) {
velocity = Double.parseDouble( event.getActionCommand() );
spanField.setText( velocity_string );
status_b++;
// process trajectory_angle event
if( event.getSource() == trajectory_angleField ) {
trajectory_angle = Double.parseDouble( event.getActionCommand() );
spanField.setText( trajectory_angle_string );
status_b++;
// process time_increment event
if( event.getSource() == time_incrementField ) {
time_increment = Double.parseDouble( event.getActionCommand() );
spanField.setText( time_increment_string );
status_b++;
// process rotation_factor event
if( event.getSource() == rotation_factorField ) {
rotation_factor = Double.parseDouble( event.getActionCommand() );
spanField.setText( rotation_factor_string );
status_b++;
// process startButton event
if ( event.getSource() == startButton && status_b == 9 ) {
strtb();
} // end method event handler
public void strtb()
startButton.addActionListener(
new ActionListener() { // anonymous inner class
// set text in resultsArea
public void actionPerformed( ActionEvent event )
calculate();
results();
resultsArea.setText( results() );
}// end method actionPerformed1
} // end anonymous inner class1
); // end call to addActionlistener1
} // end method strtb
public void reset()
resetButton.addActionListener(
new ActionListener() { // anonymous inner class
// set text in resultsArea
public void actionPerformed( ActionEvent event )
span_string = "";
chord_string = "";
thickness_string = "";
mass_string = "";
altitude_string = "";
velocity_string = "";
trajectory_angle_string = "";
time_increment_string = "";
rotation_factor_string = "";
results_string = "";
spanField.setText( span_string );
chordField.setText( chord_string );
thicknessField.setText( thickness_string );
massField.setText( mass_string );
altitudeField.setText( altitude_string );
velocityField.setText( velocity_string );
trajectory_angleField.setText( trajectory_angle_string );
time_incrementField.setText( time_increment_string );
rotation_factorField.setText( rotation_factor_string );
resultsArea.setEditable( true );
resultsArea.setText( results_string );
resultsArea.setEditable( false );
span = 0;
chord = 0;
thickness = 0;
mass = 0;
altitude = 0;
velocity = 0;
trajectory_angle = 0;
time_increment = 0;
rotation_factor = 0;
distance = 0;
velocity_fps = 0;
elapsed_time = 0;
} // end method actionPerformed2
} // end anonymous inner class2
); // end call to addActionlistener2
} // end method reset
public void cont()
//later
public void calculate()
distance = 1;
altitude = 2;
trajectory_angle = 3;
velocity_fps = 4;
elapsed_time = 5;
public String results()
results_string =
"Distance =\t\t" + distance + " miles\n"
+ "Altitude =\t\t" + altitude + " feet\n"
+ "Trajectory Angle =\t" + trajectory_angle + " degrees\n"
+ "Velocity =\t\t" + velocity_fps + " feet per second\n"
+ "Elapsed Time =\t\t" + elapsed_time + " seconds\n"
+ "\nstatus_a = " + status_a + "\nstatus_b = "
+ status_b + "\nstatus_c = " + status_c;
return results_string;
public void start()
if(status_a == 0 )
strtb();
if (status_b == 0)
reset();
}// end method start
} //end class trajectory_b
Similar Messages
-
Hi,
I have a simple applet of a sound calculator. I have two events - one for capturing data from the buttons pressed on the applet and the other to output the sound associated with the button. However only one method is working ie: the sound! If I put the the sound method in comments however the other method works. Can somebody help me pls?
import java.awt.*;
import java.lang.*;
import java.applet.Applet;
//===================
// Calculator Applet
//===================
public class Calc extends Applet
// member
TextField text;
String sText1, sText2;
double dReg1, dReg2, dMem;
String sOperator;
boolean isFixReg;
Object arg;
Button plus, minus, division, times, SQRT, changesign, getmemory, memorycancelled, memorysave, equals;
Button numbers[], extras[];
// constructor
public Calc()
Panel pFrame = new Panel();
pFrame.setLayout(new FlowLayout());
text = new TextField("");
text.setForeground(Color.black);
text.setEditable(false);
Panel pCalc = new Panel();
pCalc.setLayout(new BorderLayout(0, 10));
pCalc.add("North", text);
pFrame.add("Center", pCalc);
Dimension dSize= pCalc.size();
dSize.width = dSize.width + 20;
dSize.height = dSize.height + 20;
pFrame.resize(dSize);
Panel pKey = new Panel();
pKey.setLayout(new GridLayout(6, 3, 3, 3));
add("Center", pKey);
numbers = new Button [10];
extras = new Button [2];
pKey.add(extras[0] = new Button("C"));
pKey.add(getmemory = new Button("MR"));
pKey.add(memorycancelled = new Button("M-"));
pKey.add(memorysave = new Button("M+"));
pKey.add(numbers[7] = new Button("7"));
pKey.add(numbers[8] = new Button("8"));
pKey.add(numbers[9] = new Button("9"));
pKey.add(division = new Button("/"));
pKey.add(numbers[4] = new Button("4"));
pKey.add(numbers[5] = new Button("5"));
pKey.add(numbers[6] = new Button("6"));
pKey.add(times = new Button("*"));
pKey.add(numbers[1] = new Button("1"));
pKey.add(numbers[2] = new Button("2"));
pKey.add(numbers[3] = new Button("3"));
pKey.add(minus = new Button("-"));
pKey.add(numbers[0] = new Button("0"));
pKey.add(extras[1] = new Button("."));
pKey.add(equals = new Button("="));
pKey.add(plus = new Button("+"));
pKey.add(SQRT = new Button("SQRT"));
pKey.add(changesign = new Button("+/-"));
pCalc.add("South", pKey);
setLayout(new BorderLayout(0, 0));
add("North", pFrame);
setBackground(Color.darkGray);
dReg1 = 0.0d;
dReg2 = 0.0d;
dMem = 0.0d;
sOperator = "";
text.setText("0");
isFixReg = true;
// event handler
public boolean action(Event event, Object arg)
// numeric key input
if ("C".equals(arg))
dReg1 = 0.0d;
dReg2 = 0.0d;
sOperator = "";
text.setText("0");
isFixReg = true;
else if (("0".equals(arg)) | ("1".equals(arg)) | ("2".equals(arg))
| ("3".equals(arg)) | ("4".equals(arg)) | ("5".equals(arg))
| ("6".equals(arg)) | ("7".equals(arg)) | ("8".equals(arg))
| ("9".equals(arg)) | (".".equals(arg)))
if (isFixReg)
sText2 = (String) arg;
else
sText2 = text.getText() + arg;
text.setText(sText2);
isFixReg = false;
// operations
else if (("+".equals(arg)) | ("-".equals(arg)) | ("*".equals(arg)) |
("*".equals(arg)) | ("SQRT".equals(arg)) |("+/-".equals(arg))|("=".equals(arg)))
sText1 = text.getText();
dReg2 = (Double.valueOf(sText1)).doubleValue();
dReg1 = Calculation(sOperator, dReg1, dReg2);
Double dTemp = new Double(dReg1);
sText2 = dTemp.toString();
text.setText(sText2);
sOperator = (String) arg;
isFixReg = true;
// memory read operation
else if ("memorysave".equals(arg))
Double dTemp = new Double(dMem);
sText2 = dTemp.toString();
text.setText(sText2);
sOperator = "";
isFixReg = true;
// memory add operation
else if ("getmemory".equals(arg))
sText1 = text.getText();
dReg2 = (Double.valueOf(sText1)).doubleValue();
dReg1 = Calculation(sOperator, dReg1, dReg2);
Double dTemp = new Double(dReg1);
sText2 = dTemp.toString();
text.setText(sText2);
dMem = dMem + dReg1;
sOperator = "";
isFixReg = true;
// memory sub operation
else if ("memorycancelled".equals(arg))
sText1 = text.getText();
dReg2 = (Double.valueOf(sText1)).doubleValue();
dReg1 = Calculation(sOperator, dReg1, dReg2);
Double dTemp = new Double(dReg1);
sText2 = dTemp.toString();
text.setText(sText2);
dMem = dMem - dReg1;
sOperator = "";
isFixReg = true;
return true;
public boolean handleEvent( Event event ) {
if ( event.target == plus ) {
play( getCodeBase(), "plus.au" );
return true;
if ( event.target == minus ) {
play( getCodeBase(), "minus.au" );
return true;
if ( event.target == times ) {
play( getCodeBase(), "times.au" );
return true;
if ( event.target == division ) {
play( getCodeBase(), "division.au" );
return true;
if ( event.target == SQRT ) {
play( getCodeBase(), "SQRT.au" );
return true;
if ( event.target == changesign ) {
play( getCodeBase(), "changesign.au" );
return true;
if ( event.target == getmemory ) {
play( getCodeBase(), "getmemory.au" );
return true;
if ( event.target == memorycancelled ) {
play( getCodeBase(), "memorycancelled.au" );
return true;
if ( event.target == memorysave ) {
play( getCodeBase(), "memorysave.au" );
return true;
if ( event.target == equals ) {
play( getCodeBase(), "equals.au" );
return true;
for (int count = 0; count < numbers.length; count++){
if ( event.target == numbers[count] ) {
play( getCodeBase(), "ding.au" );
return true;
for (int count = 0; count < extras.length; count++){
if ( event.target == extras[count] ) {
play( getCodeBase(), "dong.au" );
return true;
return super.handleEvent( event );
// Calculation
private double Calculation(String sOperator, double dReg1, double dReg2)
if ("+".equals(sOperator)) dReg1 = dReg1 + dReg2;
else if ("-".equals(sOperator)) dReg1 = dReg1 - dReg2;
else if ("*".equals(sOperator)) dReg1 = dReg1 * dReg2;
else if ("/".equals(sOperator)) dReg1 = dReg1 / dReg2;
else if ("SQRT".equals(sOperator)) dReg1 = Math.sqrt (dReg1);
else if ("+/-".equals(sOperator)) dReg1 = -dReg1;
else dReg1 = dReg2;
return dReg1;
}I take it you are talking about action and handleEvent, I don't see action called any place--I put it in the "find on this page" search and your declaration is the only place it is found, so could you post one where you actually make calls appropirately for each method (how you want them implemented) and use code tags?
My old eyes, as well as others' on here, just don't pick that needle out of the haystack like they did when we were 20 years old. -
Event handling - output doubled?!
hi, i'm trying to implement some event handling through an extension of the MouseAdapter class, but the output comes out twice for some reason. code is as follows:
note: for some reason an 'i' enclosed in square brackets isn't shown in these forums, but makes things italic... any idea how to change that?!
public void mouseClicked(MouseEvent e)
p = e.getPoint() ;
for(int i = 0 ; i < myproj.length ; i++)
rect = myproj.getDshape() ;
System.out.println(rect.toString()) ;
if (rect.contains(p))
System.out.println(i) ;
System.out.println(myproj.length) ;
System.out.println("clicked one!") ;
System.out.println(p.toString()) ;
System.out.println(myproj[i].getDname() + " : " + myproj[i].getStrength() + " : " + myproj[i].getDom()) ;
wanted++ ;
System.out.println("Count: " + counter) ;
counter++ ;
} // end class MyEventHandler
however, when i click in one of the 2 rectangles on my applet, the following output is printed:
java.awt.Rectangle[x=521,y=50,width=25,height=25]
0
2
clicked one!
java.awt.Point[x=541,y=62]
tom : 4.51 : 1
Count: 0
java.awt.Rectangle[x=571,y=80,width=25,height=25]
java.awt.Rectangle[x=521,y=50,width=25,height=25]
0
2
clicked one!
java.awt.Point[x=541,y=62]
tom : 4.51 : 1
Count: 1
java.awt.Rectangle[x=571,y=80,width=25,height=25]
anyone got any ideas why it does this twice? i have also tried this with mousepressed and mousereleased as well as mouseclicked, but the same occurs...You're probably adding the mouseListener to your component twice, but you don't show that part of the code so it's hard to tell for sure.
'i' enclosed in square brackets isn't shown in these forums, but makes things italicClick on the help link at the top of the page. It explains some formatting codes you can use to make your code easier to read.
... - italic
... - highlights java keywords and comments -
Java Event Handling in JSP Pages
Dear All:
This is what I wanna do. when user enters text in my <input type="text" ... > in my JSP page, I want to take this user entered data and convert it in another language simultaneously as the user is inputting text in another textarea.
Right now the only choice I have is onChange="convert()" Javascript function.
But I dont want to use Javascript as I already have a Java class which does that for the Swing GUI client.
Is their a way i can embed java for event handling in jsp.
thanks,
Chetanonly if you use an applet, javascript, etc.
remember, jsp is server-side, not client-side
what the client sees is html or whatever (i.e. static content) -
OK, so here's a good question to ask for my first post to this site!
My current "project" is a GUI applet that does real-time interactions on a set of objects and user input. I'm using double buffering, event handling (from the keyboard) and multiple threads to handle the categories of "user input and graphics" and "world state updating." Here is a rough overview of how the program is layed out:
// keyboard input status class
class Keyboard extends KeyListener {
static int[] code = new int[7]; // contains keycodes of interesting keys
static boolean[] status = new boolean[7]; // status of keys (true=pressed)
static boolean getStatus(int key) {
return status[key];
void keyPressed(KeyEvent e) {
for(int i = 6; i >= 0; i--)
if(code[i] == e.code)
status[i] = true;
void keyReleased(KeyEvent e) {
for(int i = 6; i >= 0; i--)
if(code[i] == e.code)
status[i] = false;
// main program applet
class Program extends Applet implements Runnable {
static Thread thread; // main thread of applet
static Image buffer; // double buffer for offscreen rendering
static boolean running; // flag to indicate status of applet
void init() {
buffer = createImage(500, 500);
// other initializations
void destroy() {
// other disposes
void start() {
running = true;
thread = new Thread(this);
thread.start();
addKeyListener(new Keyboard()); // begin receiving input
void stop() {
running = false;
if(thread != Thread.currentThread())
thread.join(); // wait for thread to die before continuing
void run() {
double paintTimer = 0; // timer to suspend painting to buffer until necessary
double dt = 0; // difference in time between loops
while(running) {
// update timing stuff (dt and paintTimer)
// update world status
paintTimer -= dt; // to decrement painting timer
if(paintTimer <= 0) {
paintTimer = 1.0 / fps; // reset paint timer based on current fps setting
synchronized(syncObject) {
// paint world to buffer
repaint();
Thread.yield(); // to yield time to painting and user input thread
// this method is only called by the internal thread within the applet
// that is responsible for painting and event handling
void paint(Graphics g) {
// make sure painting to screen won't conflict with thread that's drawing on buffer!
synchronized(syncObject) {
g.drawImage(buffer, 0, 0, null); // do double buffering...paint buffer to screen
}So the end result is that it works fine some of the time, but every once in awhile I'll get these strange results where it'll seem as if the internal thread that handles graphics and input will get bogged down or stop responding normally, even with the Thread.yield() call from the main applet thread. I'll get results where the world will continue to be updated correctly, but the user input and onscreen rendering freeze in a particular state for a matter of seconds, and then it seems to regain control for a brief few milliseconds (hence I'll get a quick screen refresh and keyboard state change), and then it'll freeze again. Once this starts happening somewhere in the middle of execution, it continues to happen throughout that runtime session. Sometimes when I force-close the appletviewer I'll get weird native runtime exceptions that seem to occur within Sun's keyboard input manager.
Almost always it'll run perfectly for many minutes, and then all of a sudden it'll start to freeze up. Every once in awhile it freezes almost immediately after startup. I've run some testcases on it and am pretty confident it has nothing to do with the synchronization or the fact that I create a new applet thread every time the applet is restarted dynamically. Is it something happening within the event thread of the applet that I'm not aware of? Or is it something wrong with the flow of my code? Thanks for any input or help you can give! I'll be happy to send more details if needed.
Zachright before your repaint, putSystem.out.println("Is EDT? "+SwingUtilities.isEventDispatcherThread());if its printing false, then you need to do SwingUtilities.invokeLater( ... );
and put GUI updating code in the invoke later. -
Trajectory program event handling
Nobody else responded to my question on the subject "Trajectory" in Java Programming forum. See my post history for problem description and code. Perhaps the subject is more appropriate here as an event handling issue. Who has the technical savvy to attempt a solution?
(2) I wouldn't have problem with separate classes as
long as I have no inner classes and the program
essentially works. Sure, one 10,000 - line class may also work fine. However, it is reccommended do not make classes
(as well as source files) very large. The reason is that long file is more difficult to debug.
Second reason why i advised you to do that is that you mix in one class Trajectory (which is about 2000 lines long!!!) all - interface, event handling, calculations, parts responsible for 2D panel processing....
Well, this is not Java is supoposed to be used for.
(3) Creating object of class Falling object is
something I'll consider. If you could show me a brief
code example, I'll understand more.
class fallingObject
private double mass;
private double speed;
Position[] trajectory = new Position[1000]; // Create class Position each object of which holds only
// 2 variables - x and y
//all initial data related to this object
fallingObject(double mass, double speed , /* the rest ........*/)
this.mass = mass;
this.speed = speed;
moveObject();
//and so on
// some methods you need
private moveObject ()
// perform all calculations
// fill array
// etc
Now, because all except trajectory array and constructor is private you cannot change this object outside
class. This means that if something goes wrong with calculations, you check only this class and nothing else. In your case you can change some variable at lines 1352 and 122 - you have to check all program to find bug. Here you have to check only this class.
You may also supply this class with mutators and accessors
public double getMass()
return mass;
public void setMass(double mass) // only if you really need this
this.mass = mass;
The time interval
is a tricky parameter since not all calculations work
properly with input data; check input
the logic would require more
complexity and possibly cause run time problems;
automatically testing for the appropriate time
interval could also reduce program efficiency. Dont think so. You can calculate time of falling and divide it by 1000, for instance.
It will take very short time.
I don't
want to set a limit for array points to 1000 or less
since the precision becomes limited and the power of
the program can be hurt severely since the time
duration would be restricted to less than 16 2/3
minutes( 1 second per array index increment). Dont use real time simulation. There is no sence in it. You just want to show how object is falling.
Also, I
don't think the array size can't be changed during a
program run although I have set a much higher maximum
value for array size. Theres no need to change array size.
(4) Erasing data from textfields is something I desire
as a calculation reset feature since it should signal
user that it expects new data and not looking at old
data; however, I might consider additional variables
to hold the data. Well, man, it was quite irritating to type them in. So many fields. User is not stupid,
he knows that he can input other data. Almost anybody will leave this page and wont want to
fill fields again. You have to think about user, not about what you want.
(5 )BTW, what I have in the array doesn't have the
same precision as with the calculation mode. The 2D
simulation uses less precise data to become visually
practical for comprehension of users. But perhaps I
need more than one type of array, but then again,
performance could be a problem.
(6) I thought the program already does take parameters
from text fields and start again. This is what I
desire anyway so I'm not sure why I need new start
feature.
(7) Restart animation seems unaccepatble since I
prefer to treat each simulation as something based on
new calculation data.
I would have initially set up the program with OOD
emphasis, but the original intent was a java
conversion of a a C++ program that needed only a
structured program design and the conversion worked
fine. This Java program has evolved with the 2D
simulation enhancements.
When you did testing the other day, did you use
appletviewer? I looked at it on your site using Safari and run it as application also.
Appletviewer will not detect the problem
so don't rely on Appletviewer to interpret the
problem. Oddly, I wish the program behaved the same
way as what happens when using appletviewer. In fact,
if I could change 2d reset button logic to terminate
and restart the entire applet again via html, then my
problem would be solved. But I don't know if this type
of applet restart is possible or how to effect the
code change if feasible. -
I have a Jbutton ...
When i click on it.. i want it to open up the chess game in a new window and start playing..
This is my codes..
//Event handler for the Jbutton
if(event.getSource() == Start)
chess frame=new chess();
frame.setSize(500,500);
frame.setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
However.. when i click on it.. it gives me a java.lang.nullpointerException error...
the main application codes is actually an applet embedded into a frame...
Below is the class file which i wanted to link it..If it extends JFrame i can easily link it but it extends java.applet.Applet...
(public class chess extends java.applet.Applet implements MouseListener, MouseMotionListener,Runnable)
Is there a way to link it.?You may not call JFrame methods on an Applet.
Also, Applet extends from Panel which is an AWT class, therefore, heavyweight vis–a–vis Swing which is lightweight. So you must load it into a Frame. If Chess were extending JApplet you could load it into a JFrame.
//Event handler for the JButton
if(event.getSource() == startButton)
Chess applet = new Chess();
final Frame f = new Frame();
f.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
f.dispose();
f.add(applet);
f.setSize(500,500);
f.setLocation(200,200);
applet.init();
applet.start();
f.setVisible(true);
} -
Delicate ProgressMonitor/ event handling problem
Hi,
I have a delicate ProgressMonitor / event handling problem.
There exists some solution on similiar problems here in the forums, but no solution to my special problem, hope anybody can help me out.
I have a rather big project, an applet, that I've written a separate JarLoader class that will load specific jar's if the ClassLoader encounter a unloaded class, all ok so far.
But, during loading, I would like to display a ProgressBar. And here is the problem. If my custom ClassLoader intercepts a findClass -request that needs to load the class from a jar from a normal thread, this is no problem, but if the ClassLoader intercepts a findClass that needs loading a jar when inside the EventQueue -thread, this is becomming tricky!
The catch is that an event posted on the EventQueue finally needs a class that needs to be loaded, but I cannot dispatch a thread to do this and end that particular event before the class itself is loaded.
So how do I hold the current EventQueue -event needing a jar -load, Pop up a ProgressBar, then process events in the EventQueue to display the ProgressBar and update repaints in it? then return from the event that now have loaded needed class-files.
I've tried a tip described earlier in the forums by trying to handle events with this code when loading the Jar:
/** process any waiting events - use during long operations
* to update UI */
static public void doEvents() {
// need to derive from EventQueue otherwise
// don't have access to protected method dispatchEvent()
class EvtQueue extends java.awt.EventQueue {
public void doEvents() {
Toolkit toolKit = Toolkit.getDefaultToolkit();
EventQueue evtQueue = toolKit.getSystemEventQueue();
// loop whilst there are events to process
while (evtQueue.peekEvent() != null) {
try {
// if there are then get the event
AWTEvent evt = evtQueue.getNextEvent();
// and dispatch it
super.dispatchEvent(evt);
catch (java.lang.InterruptedException e) {
// if we get an exception in getNextEvent()
// do nothing
// create an instance of our new class
EvtQueue evtQueue = new EvtQueue();
// and call the doEvents method to process the events.
evtQueue.doEvents();
}Then, the loader checks
java.awt.EventQueue.isDispatchThread()to see if its' inside the eventqueue, and runs doEvents after updating the ProgressMonitor with new setProgress and setNote values.
More precise;
The loader is loading the jar like this:
(this is pseudo code, not really usable, but outlines the vital parts)
public void load() {
monitor = new ProgressMonitor(null, "Loading " + jarName, ""+jarSize + " bytes", 0, jarSize);
monitor.setMillisToDecideToPopup(0);
monitor.setMillisToPopup(0);
// reading jar info code here ...
JarEntry zip = input.getNextJarEntry();
for (;zip != null;) {
// misc file handling here... total = current bytes read
monitor.setProgress(total);
monitor.setNote(note);
if (java.awt.EventQueue.isDispatchThread()) {
doEvents();
zip = input.getNextJarEntry();
monitor.close();
}When debugging doEvents(), there is never any events pending in peekEvents(), even if I tries to put a invokeLater() to run the setProgress on the monitor, why? If it had worked, the doEvents() code would have saved my day...
So, this is where I'm totally stuck...Just want to describe how I did this using spin from http://spin.sourceforge.net
This example is not pretty, but it can probably help others understanding spin. Cancelling the ProgressMonitor is not implemented, but can easily be done by checking on ProgressMonitor.isCanceled() in
the implementation code.
First, I create a bean for displaying and run a ProgressMonitor:
Spin requires an Interface and an Implementation, but that's just nice programming practice :-)
import java.util.*;
public interface ProgressMonitorBean {
public void start(); // start spinning
public void cancel(); // cancel
public int getProgress(); // get the current progress value
public void setProgress(int progress); // set progress value
public void addObserver(Observer observer); // observer on the progressValue
}Then, I created the implementation:
import java.util.*;
import javax.swing.ProgressMonitor;
import java.awt.*;
public class ProgressMonitorBeanImpl extends Observable implements ProgressMonitorBean {
private ProgressMonitor monitor;
private boolean cancelled;
private int progress = 0;
private int currentprogress = 0;
public ProgressMonitorBeanImpl(Component parent, Object message, String note, int min, int max) {
monitor = new ProgressMonitor(parent, message, note, min, max);
monitor.setMillisToDecideToPopup(0);
monitor.setMillisToPopup(0);
public void cancel() {
monitor.close();
public void start() {
cancelled = false;
progress = 0;
currentprogress = 0;
while (progress < m_cMonitor.getMaximum()) {
try {
synchronized (this) {
wait(50); // Spinning with 50 ms delay
if (progress != currentprogress) { // change only when different from previous value
setChanged();
notifyObservers(new Integer(progress));
monitor.setProgress(progress);
currentprogress = progress;
} catch (InterruptedException ex) {
// ignore
if (cancelled) {
break;
public int getProgress() {
return progress;
public void setProgress(int progress) {
this.progress = progress;
}in my class/jarloader code, something like this is done:
public void load() {
ProgressMonitorBean monitor = (ProgressMonitorBean)Spin.off(new ProgressMonitorBeanImpl(null, "Loading " + url,"", 0, jarSize));
Thread t = new Thread() {
public void run() {
JarEntry zip = input.getNextJarEntry();
for (;zip != null;) {
// misc file handling here... progress = current bytes read
monitor.setProgress(progress);
t.start(); // fire off loadin into own thread to do time consuming work
monitor.start(); // this will spin events on monitor and block until progress = max
monitor.cancel(); // Just make sure ProgressMonitor is closed
}The beautiful thing here is that Spin is taking care of weither the load() is inside the dispatch thread or not, making the code much simpler and cleaner to understand.
The ProgressMonitorBeanImplementation could been made much nicer and more complete, but I was in a hurry to check if it worked out. And it did! This will be applied on a lot of gui -components that blocks the event-queue in our project, making it much more responsive.
Hope this will help others in similiar situations! Thanks again svenmeier for pointing me to the spin -project. -
How can I execute an external program from within a button's event handler?
I am using Tomcat ApacheTomcat 6.0.16 with Netbeans 6.1 (with the latest JDK/J2EE)
I need to execute external programs from an event handler for a button on a JSF page (the program is compiled, and extremely fast compared both to plain java and especially stored procedures written in SQL).
I tried what I'd do in a standalone program (as shown in the appended code), but it didn't work. Instead I received text saying the program couldn't be found. This error message comes even if I try the Windows command "dir". I thought with 'dir' I'd at least get the contents of the current working directory. :-(
I can probably get by with cgi on Apache's httpd server (or, I understand tomcat supports cgi, but I have yet to get that to work either), but whatever I do I need to be able to do it from within the button's event handler. And if I resort to cgi, I must be able to maintain session jumping from one server to the other and back.
So, then, how can I do this?
Thanks
Ted
NB: The programs that I need to run do NOT take input from the user. Rather, my code in the web application processes user selections from selection controls, and a couple field controls, sanitizes the inoputs and places clean, safe data in a MySQL database, and then the external program I need to run gets safe data from the database, does some heavy duty number crunching, and puts the output data into the database. They are well insulated from mischeif.
NB: In the following array_function_test.pl was placed in the same folder as the web application's jsp pages, (and I'd tried WEB-INF - with the same result), and I DID see the file in the application's war file.
try {
java.lang.ProcessBuilder pn = new java.lang.ProcessBuilder("array_function_test.pl");
//pn.directory(new java.io.File("K:\\work"));
java.lang.Process pr = pn.start();
java.io.BufferedInputStream bis = (java.io.BufferedInputStream)pr.getInputStream();
String tmp = new String("");
byte b[] = new byte[1000];
int i = 0;
while (i != -1) {
bis.read(b);
tmp += new String(b);
getSelectionsDisplayTextArea().setText(getSelectionsDisplayTextArea().getText() + "\n\n" + tmp);
} catch (java.io.IOException ex) {
getSelectionsDisplayTextArea().setText(getSelectionsDisplayTextArea().getText() + "\n\n" + ex.getMessage());
}Hi Fonsi!
One way to execute an external program is to use the System Exec.vi. You find it in the functions pallet under Communication.
/Thomas -
Copying text to the clipboard in AVDocDidOpen event handler causes Acrobat 9 to crash
I'm trying to copy the filename of a document to the clipboard in a plugin with my AVDocDidOpen event handler. It works for the first file opened; however when a second file is opened, Acrobat crashes. The description in the application event log is: "Faulting application acrobat.exe, version 9.1.0.163, faulting module gdi32.dll, version 5.1.2600.5698, fault address 0x000074cc."
I've confirmed that the specific WIN32 function that causes this to happen is SetClipboardData(CF_TEXT, hText); When that line is commented out and remaining code is left unchanged, Adobe doesn't crash.
Is there an SDK function that I should be using instead of WIN32's SetClipboardData()? Alternately, are there other SDK functions that I need to call be before or after I call SetClipboardData()
Bill EricksonLeonard,
I tried it with both "DURING, HANDLER, END_HANDLER" and "try catch," as shown below. However, it doesn't crash in the event handler; it crashes later, so the HANDLER/catch block is never hit.
The string that's passed to SetClipboardData() is good, because I'm able to paste it into the filename text box of the print dialog when I try to create the "connector line" PDF. I also got rid of all the string manipulation and tried to pass a zero-length string to the clipboard but it still crashes.
Here's the code:
ACCB1 void ACCB2 CFkDisposition::myAVDocDidOpenCallback(AVDoc doc, Int32 error, void *clientData)
PDDoc pdDoc = AVDocGetPDDoc(doc);
char* pURL = ASFileGetURL(PDDocGetFile(annotDataRec->thePDDoc));
if (pURL) {
if (strstr(pURL, "file://") && strstr(pURL, "Reviewed.pdf")) {
// Opened from file system so copy filename to clipboard for connector line report
char myURL[1000];
strcpy(myURL, pURL);
ASfree(pURL); // Do this before we allocate a Windows handle just in case Windows messes with this pointer
pURL = NULL;
HGLOBAL hText = GlobalAlloc(GMEM_MOVEABLE, 1000);
if (hText) {
try
// Skip path info and go right to filename
char *pText = (char *)GlobalLock(hText);
char *pWork = strrchr(myURL,'/');
if (pWork) {
strcpy(pText, pWork+1);
} else {
strcpy(pText, myURL);
char *pEnd = pText + strlen(pText); // Get null terminator address
// Replace "%20" in filename with " "
pWork = strstr(pText, "%20");
while (pWork) {
*pWork = ' ';
memmove(pWork+1, pWork+3, (pEnd - (pWork+2)));
pWork = strstr(pText, "%20");
// Append a new file extension
pWork = strstr(pText, ".pdf");
*pWork = 0; // truncate the string before ".pdf"
strcat(pWork,".Connectors.pdf");
GlobalUnlock(hText); // Must do this BEFORE SetClipboardData()
// Write it to the clipboard
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(CF_TEXT, hText); // Here's the culprit
CloseClipboard();
GlobalFree(hText);
} catch (char * str) {
AVAlertNote(str);
if (pURL)
ASfree(pURL); -
Unable to get automatic event handling for OK button.
Hello,
I have created a form using creatobject. This form contains an edit control and Search, Cancel buttons. I have set the Search buttons UID to "1" so it can handle the Enter key hit event. Instead its caption changes to Update when i start typing in the edit control and it does not respond to the Enter key hit. Cancel happens when Esc is hit.
My code looks like this -
Dim oCreationParams As SAPbouiCOM.FormCreationParams
oCreationParams = SBO_Application.CreateObject(SAPbouiCOM.BoCreatableObjectType.cot_FormCreationParams)
oCreationParams.UniqueID = "MySearchForm"
oCreationParams.BorderStyle = SAPbouiCOM.BoFormBorderStyle.fbs_Sizable
Dim oForm As SAPbouiCOM.Form = SBO_Application.Forms.AddEx(oCreationParams)
oForm.Visible = True
'// set the form properties
oForm.Title = "Search Form"
oForm.Left = 300
oForm.ClientWidth = 500
oForm.Top = 100
oForm.ClientHeight = 240
'// Adding Items to the form
'// and setting their properties
'// Adding an Ok button
'// We get automatic event handling for
'// the Ok and Cancel Buttons by setting
'// their UIDs to 1 and 2 respectively
oItem = oForm.Items.Add("1", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
oItem.Left = 5
oItem.Width = 65
oItem.Top = oForm.ClientHeight - 30
oItem.Height = 19
oButton = oItem.Specific
oButton.Caption = "Search"
'// Adding a Cancel button
oItem = oForm.Items.Add("2", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
oItem.Left = 75
oItem.Width = 65
oItem.Top = oForm.ClientHeight - 30
oItem.Height = 19
oButton = oItem.Specific
oButton.Caption = "Cancel"
oItem = oForm.Items.Add("NUM", SAPbouiCOM.BoFormItemTypes.it_EDIT)
oItem.Left = 105
oItem.Width = 140
oItem.Top = 20
oItem.Height = 16
Dim oEditText As SAPbouiCOM.EditText = oItem.Specific
What changes do i have to make to get the enter key to work?
Thanks for your help.
Regards,
SheetalHello Felipe,
Thanks for pointing me to the correct direction.
So on refering to the documentation i tried out a few things. But I am still missing something here.
I made the following changes to my code -
oForm.AutoManaged = True
oForm.SupportedModes = 1 ' afm_Ok
oItem = oForm.Items.Add("1", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
oItem.Left = 5
oItem.Width = 65
oItem.Top = oForm.ClientHeight - 30
oItem.Height = 19
oItem.SetAutoManagedAttribute(SAPbouiCOM.BoAutoManagedAttr.ama_Visible, 1, SAPbouiCOM.BoModeVisualBehavior.mvb_Default)
oButton = oItem.Specific
oButton.Caption = "OK"
AND
oForm.Mode = SAPbouiCOM.BoFormMode.fm_OK_MODE
oItem = oForm.Items.Add("1", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
oItem.Left = 5
oItem.Width = 65
oItem.Top = oForm.ClientHeight - 30
oItem.Height = 19
oItem.AffectsFormMode = False
I get the same behaviour OK button changes to update and enter key does not work.
Could you please tell me find what is it that i am doing wrong?
Regards,
Sheetal -
Dropdown box - which event handler to use ?
I am having trouble with setting the readonly property (via Javascript) of the adjacent textbox to my dropdown box when the index value is a certain number.
I tried using MouseUp, MouseDown, and even OnBlur....but the readonly does not seem to be getting set to true or false consistently.
Could this be a timing issue ? The textbox that I am trying to control is the next tab-order control in the list of controls for this page.
This same logic is working fine in the MouseUp event handler for check boxes. So I am just wondering if this is a bug or must my implementation change to accomodate dropdown boxes ? For instance, should I move the logic to the Enter event handler of the textbox instead ? Can a control's own eventhandler set itself to readonly when it is the active form field ?After tons and tons of testing time, I've come to the conclusion that dropdowns are totally buggy in 11.0.07 release of Acrobat Pro.
Even if you set the "commit values immediately", you get the PRIOR selected item's value as the event value, not the CURRENT one.
This occurs in a Validate event handler script. I have not been able to use any other event handlers for a dropdown except the OnBlur....and then, for my purposes, IT'S TOO LATE !!!
This is totally worthless as I need to setFocus() and set fields to readonly based on the immediate dropdown offset or face value. -
Input value given on web page is not getting pickedup in event handler
Hi friends,
I have created one simple page in SE80 with program with flow logic option, in which I would like to show business partner details from BUT000 table with the input of partner number. But the thing is the input value(partner no.)which I am giving on web page is not getting picked up in selection in event handler though I am giving input value it is becoming initial while selecting. What could be the reason?
Below I am mentioning the code which I have written in even handler for OnInputProcessing event.
CASE EVENT_ID.
WHEN 'select'.
NAVIGATION->SET_PARAMETER( 'partner' ).
SELECT * FROM but000 INTO TABLE I_but000 WHERE partner BETWEEN partner AND partner1.
WHEN OTHERS.
ENDCASE.
Thanks in advance,
SteveHi Abhinav,
I tried with the one you posted. But it is giving run time error as shown below.
Note
The following error text was processed in the system CRD : Access via 'NULL' object reference not possible.
The error occurred on the application server crmdev_CRD_00 and in the work process 0 .
The termination type was: RABAX_STATE
The ABAP call stack was:
Method: ONINPUTPROCESSING of program CLO24DDFJW575HVAQVJ89KWHEHC9OCP
Method: %_ONINPUTPROCESSING of program CL_O24DDFJW575HVAQVJ89KWHEHC9OCP
Method: DO_REQUEST of program CL_BSP_PAGE===================CP
Method: ON_REQUEST of program CL_BSP_RUNTIME================CP
Method: IF_HTTP_EXTENSION~HANDLE_REQUEST of program CL_HTTP_EXT_BSP===============CP
Method: EXECUTE_REQUEST_FROM_MEMORY of program CL_HTTP_SERVER================CP
Function: HTTP_DISPATCH_REQUEST of program SAPLHTTP_RUNTIME
Module: %_HTTP_START of program SAPMHTTP
Regards,
Steve -
How do I create an Event Handler for an Execute SQL Task in SSIS if its result set is empty
So the precedence on my entire package executing is based on my first SELECT of my Table and an updatable column. If that SELECT results in an empty result set, how do I create an Event Handler to handle an empty result set?
A Newbie to SSIS.
I appreciate your review and am hopeful for a reply.
PSULionRPDepends upon what you want to do in the eventhandler. this is what you can do
Store the result set from the Select to a user variable.
Pass this user variable to a Script task.
In the Script task do whatever you want to do including failing the package this can be done by failing the script task, which in turns fails the package. something like
Dts.TaskResult = Dts.Results.Failure
Abhinav http://bishtabhinav.wordpress.com/ -
Swing: when trying to get the values from a JTable inside an event handler
Hi,
I am trying to write a graphical interface to compute the Gauss Elimination procedure for solving linear systems. The class for computing the output of a linear system already works fine on console mode, but I am fighting a little bit to make it work with Swing.
I put two buttons (plus labels) and a JTextField . The buttons have the following role:
One of them gets the value from the JTextField and it will be used to the system dimension. The other should compute the solution. I also added a JTable so that the user can type the values in the screen.
So whenever the user hits the button Dimensiona the program should retrieve the values from the table cells and pass them to a 2D Array. However, the program throws a NullPointerException when I try to
do it. I have put the code for copying this Matrix inside a method and I call it from the inner class event handler.
I would thank you very much for the help.
Daniel V. Gomes
here goes the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import AdvanceMath.*;
public class MathF2 extends JFrame {
private JTextField ArrayOfFields[];
private JTextField DimOfSis;
private JButton Calcular;
private JButton Ativar;
private JLabel label1;
private JLabel label2;
private Container container;
private int value;
private JTable DataTable;
private double[][] A;
private double[] B;
private boolean dimensionado = false;
private boolean podecalc = false;
public MathF2 (){
super("Math Calcs");
Container container = getContentPane();
container.setLayout( new FlowLayout(FlowLayout.CENTER) );
Calcular = new JButton("Resolver");
Calcular.setEnabled(false);
Ativar = new JButton("Dimensionar");
label1 = new JLabel("Clique no bot�o para resolver o sistema.");
label2 = new JLabel("Qual a ordem do sistema?");
DimOfSis = new JTextField(4);
DimOfSis.setText("0");
JTable DataTable = new JTable(10,10);
container.add(label2);
container.add(DimOfSis);
container.add(Ativar);
container.add(label1);
container.add(Calcular);
container.add(DataTable);
for ( int i = 0; i < 10 ; i ++ ){
for ( int j = 0 ; j < 10 ; j++) {
DataTable.setValueAt("0",i,j);
myHandler handler = new myHandler();
Calcular.addActionListener(handler);
Ativar.addActionListener(handler);
setSize( 500 , 500 );
setVisible( true );
public static void main ( String args[] ){
MathF2 application = new MathF2();
application.addWindowListener(
new WindowAdapter(){
public void windowClosing (WindowEvent event)
System.exit( 0 );
private class myHandler implements ActionListener {
public void actionPerformed ( ActionEvent event ){
if ( event.getSource()== Calcular ) {
if ( event.getSource()== Ativar ) {
//dimensiona a Matriz A
if (dimensionado == false) {
if (DimOfSis.getText()=="0") {
value = 2;
} else {
value = Integer.parseInt(DimOfSis.getText());
dimensionado = true;
Ativar.setEnabled(false);
System.out.println(value);
} else {
Ativar.setEnabled(false);
Calcular.setEnabled(true);
podecalc = true;
try {
InitValores( DataTable, value );
} catch (Exception e) {
System.out.println("Erro ao criar matriz" + e );
private class myHandler2 implements ItemListener {
public void itemStateChanged( ItemEvent event ){
private void InitValores( JTable table, int n ) {
A = new double[n][n];
B = new double[n];
javax.swing.table.TableModel model = table.getModel();
for ( int i = 0 ; i < n ; i++ ){
for (int j = 0 ; j < n ; j++ ){
Object temp1 = model.getValueAt(i,j);
String temp2 = String.valueOf(temp1);
A[i][j] = Double.parseDouble(temp2);What I did is set up a :
// This code will setup a listener for the table to handle a selection
players.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ListSelectionModel rowSM = players.getSelectionModel();
rowSM.addListSelectionListener(new Delete_Player_row_Selection(this));
//Class will take the event and call a method inside the Delete_Player object.
class Delete_Player_row_Selection
implements javax.swing.event.ListSelectionListener
Delete_Player adaptee;
Delete_Player_row_Selection (Delete_Player temp)
adaptee = temp;
public void valueChanged (ListSelectionEvent listSelectionEvent)
adaptee.row_Selection(listSelectionEvent);
in the row_Selection function
if(ex.getValueIsAdjusting()) //To remove double selection
return;
ListSelectionModel lsm = (ListSelectionModel) ex.getSource();
if(lsm.isSelectionEmpty())
System.out.println("EMtpy");
else
int selected_row = lsm.getMinSelectionIndex();
ResultSetTableModel model = (ResultSetTableModel) players.getModel();
String name = (String) model.getValueAt(selected_row, 1);
Integer id = (Integer) model.getValueAt(selected_row, 3);
This is how I got info out of a table when the user selected it
Maybe you are looking for
-
How to switch from one iTunes account to another on iPad ?
Hi there, I was using an old iTunes account until it went all weird. So I created a new iTunes account and I'm wondering how to get these onto my iPod touch 4th gen and iPad 1st gen ? It comes up under the iTunes store ( at the bottom ) but when I go
-
What do I need to know to write a window application to send email.
Tell me please what I need to write an API to send e-mail. I am a starter.
-
Help desk cannot assign retention policies to new mailboxes
I am running Exchange 2010 SP1. I would like to give my help desk the ability to create new mailboxes. When a new mailbox is created, we select the option to assign a Retention policy to it. I added the help desk members to the "Recipient Manageme
-
Getting the Price details in demantra
Hi all, Using demantra version 7.3.1 In demantra data model I haven't configured my price details( from flat file),Besides I had done build model successfully. Now I have the requirement to show the series like Price ,revenue forecast etc in my works
-
How to achieve grouping of data based on one column
Hello PL/SQL Gurus/experts, I am using Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production version I have following table - DROP TABLE T2; create table T2(Manager,Employee) as select 'Nikki','Ram' from dual union all select '