Event Handling in Swing

Hi,
I've a JTextField below which I have a single column table which contains some data. As I enter some character in the text field, the names in the table should sort automatically in that order. It's something like typing mail.yahoo.com. As soon as I type 'm' the address bar will display all the links starting with m and when I type 'ma' it shows links starting with ma and son on. Pls advise.

Hi,
maybe this can help you: http://www.javaworld.com/javaworld/jw-02-2001/jw-0216-jfile_p.html
Regards,
Michael

Similar Messages

  • Determine event handler for swing components from the API browser

    Is there a way to determine what event handlers are assocaited with the different swing classes. For example JTextField is associated to ActionListener, and JCheckbox uses the event handle ItemListener. Is there a way to determine this by looking at the class via the Java API?

    Yes, there is. You'll observe that JTextField has an "addActionListener(ActionListener)" method, for a start. And JTextField is a subclass of JTextComponent, which has "addCaretListener(CaretListener)" and "addInputMethodListener(InputMethodListener)" methods. And JTextComponent is a subclass of JComponent, which has an "addAncestorListener(AncestorListener)" method. And so on... there are more. All of this can be found in the API documentation by looking for methods whose names start with "add".

  • Differnence between two codes of event handling

    hello i am learning event handling in swing but confused between two codes :-
    the first code of event handling is given in book "head first java " and working fine
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Swingdemo implements ActionListener {
        JButton jbut = new JButton("Click me");
          public void go(){
            JFrame jfrm = new JFrame(" sample swing");
            JLabel jlab = new JLabel("hello Swing");
            jfrm.add(BorderLayout.NORTH,jlab);
            jfrm.add(BorderLayout.CENTER,jbut);
            jfrm.setVisible(true);
            jbut.addActionListener(this); 
            jfrm.setSize(100,100);
            jfrm.setDefaultCloseOperation(jfrm.EXIT_ON_CLOSE);
       public static void main(String[] args) {
            Swingdemo obj = new Swingdemo();
            obj.go();
    public void actionPerformed(ActionEvent e)
        jbut.setText("i have been clicked");
    }}THe second code which i think is fine is giving the following error :-
    C:\java\iodemo\src\Swingdemo.java:26: non-static variable jbut cannot be referenced from a static context
            jfrm.add(BorderLayout.CENTER,jbut);
    C:\java\iodemo\src\Swingdemo.java:28: non-static variable this cannot be referenced from a static context
            jbut.addActionListener(this); 
    C:\java\iodemo\src\Swingdemo.java:28: non-static variable jbut cannot be referenced from a static context
            jbut.addActionListener(this);  the second code is as follows :-
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Swingdemo implements ActionListener {
    public static void main(String[] args) {
    JFrame jfrm = new JFrame(" sample swing");
    JLabel jlab = new JLabel("hello Swing");
    jfrm.add(BorderLayout.NORTH,jlab);
    jfrm.add(BorderLayout.CENTER,jbut);
    jfrm.setVisible(true);
    jbut.addActionListener(this);
    jfrm.setSize(100,100);
    jfrm.setDefaultCloseOperation(jfrm.EXIT_ON_CLOSE);
    JButton jbut = new JButton("Click me");
    public void actionPerformed(ActionEvent e)
    jbut.setText("i have been clicked");
    Plz help me wat this error means that not static variable cannot be reffered from static context .
    thanks

    There are multiple problems in your 2nd set of code. You call this:
    jfrm.add(BorderLayout.CENTER,jbut);
    Before you actually create the jbut button:
    JButton jbut = new JButton("Click me");
    But based on the error message, you have another 'jbut' variable somewhere that's not included in the code you posted, and that's the one it's complaining about being referenced in a static context.
    The problem with the static context is because all your code is in the static void main method. In that method, a Swingdemo instance doesn't exist yet, therefore any non-static variables won't exist yet either. If you move all that code into the Swingdemo constructor, and just have main create a new Swingdemo instance, that should do it.

  • 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

  • Event Handling - Swing Window to Console Switch

    I have a serious problem with an app I am writing - I have a swing 'main menu' system built around a standard JFrame which calls a new instance of another class. This other class takes input from the keyboard and is displayed in the standard console window; i.e Using the standard System.out.print() syntax.
    My problem is the Swing window will not release the input stream to allow the conole to take input from the keyboard. I have implemented inner-classes within the 'main menu's' class for event handling purposes; in this case the mouse-clicks of the menu's JButton components. The problem only manifests itself when the inner-class' event handling code is called - I wrote some test methods to call the console classes code without using the inner-class' and the console works perfectly. It is my conclusion, therefore, that the calling of the console-based method from within the inner-class of the Swing super-class reserves the input for the Swing components, failing to reactivate the console. I have tried creating new InputStream objects but to no avail.
    Does anyone know how to release or terminate the methods within the inner-classes (they are all void / no return type as they implement the ActionListener abstract class)? This, I hope, will return the focus to the console.
    Any advice would be most greatfully received.
    LEC.

    If you were to have your connection object declared so that it could be referenced from anywhere in your class then you could use it in you actionPerformed method. For example:
    public class Test extends JFrame
    &nbsp&nbsp&nbspprivate Connection con = null;
    &nbsp&nbsp&nbsppublic void actionPerformed(ActionEvent e)
    &nbsp&nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbspMyDetails appmydet = new MyDetails(con, id); //connection, userID
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbspappmydet.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
    &nbsp&nbsp&nbsp}
    &nbsp&nbsp&nbsppublic void setConnection(Connection theCon)
    &nbsp&nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbspcon = theCon;
    &nbsp&nbsp&nbsp}

  • Swing locks up during event handling of a simple button... bug or feature?

    I have the following code:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JToolBar;
    import javax.swing.SwingUtilities;
    public class Test extends JFrame {
         private static final long serialVersionUID = 1L;
         private JButton button;
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Runnable(){public void run(){new Test();}});
         public Test()
              setSize(200,00);
              setLayout(new BorderLayout());
              JToolBar toolbar = new JToolBar();
              button = new JButton("button");
              button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { button.setEnabled(false);}});
              toolbar.add(button);
              getContentPane().add(toolbar, BorderLayout.SOUTH);
              JPanel panel = new JPanel();
              panel.setPreferredSize(new Dimension(200,10000));
              for(int i=0;i<10000; i++) { panel.add(new JLabel(""+(Math.random()*1000))); }
              JScrollPane scrollpane = new JScrollPane();
              scrollpane.getViewport().add(panel);
              scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              scrollpane.setPreferredSize(getSize());
              scrollpane.setSize(getSize());
              getContentPane().add(scrollpane, BorderLayout.CENTER);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLocationRelativeTo(null);
              setVisible(true);
              pack();
    }This code is lethal to swing: when pressing the button, for no identifiable reason the entire UI will lock up, even though all the event handler is doing is setting the button's "enabled" property to false. The more content is located in the panel, the longer this locking takes (set -Xmx1024M and the label loop to 1000000 items, then enjoy timing how long it takes swing to realise that all it has to do is disable the button...)
    Does anyone here know of how to bypass this behaviour (and if so, how?), or is it something disastrous that cannot be coded around because it's inherent Swing behaviour?
    I tried putting the setEnabled(false) call in a WorkerThread... that does nothing. It feels very much like somehow all components are locked, while the entire UI is revalidated, but timing revalidation shows that the panel revalidates in less than 50ms, after which Swing's stalled for no reason that I can identify.
    Bug? Feature?
    how do I make it stop doing this =(
    - Mike

    However, if you replace "setEnabled(false)" with "setForeground(Color.red)") the change is instant,I added a second button to the toolbar and invoked setEnabled(true) on the first button and the change is instant as well. I was just looking at the Component code to see the difference between the two. There are a couple of differences:
        public void setEnabled(boolean b) {
            enable(b);
         * @deprecated As of JDK version 1.1,
         * replaced by <code>setEnabled(boolean)</code>.
        @Deprecated
        public void enable() {
            if (!enabled) {
                synchronized (getTreeLock()) {
                    enabled = true;
                    ComponentPeer peer = this.peer;
                    if (peer != null) {
                        peer.enable();
                        if (visible) {
                            updateCursorImmediately();
                if (accessibleContext != null) {
                    accessibleContext.firePropertyChange(
                        AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
                        null, AccessibleState.ENABLED);
         * @deprecated As of JDK version 1.1,
         * replaced by <code>setEnabled(boolean)</code>.
        @Deprecated
        public void enable(boolean b) {
            if (b) {
                enable();
            } else {
                disable();
         * @deprecated As of JDK version 1.1,
         * replaced by <code>setEnabled(boolean)</code>.
        @Deprecated
        public void disable() {
            if (enabled) {
                KeyboardFocusManager.clearMostRecentFocusOwner(this);
                synchronized (getTreeLock()) {
                    enabled = false;
                    if (isFocusOwner()) {
                        // Don't clear the global focus owner. If transferFocus
                        // fails, we want the focus to stay on the disabled
                        // Component so that keyboard traversal, et. al. still
                        // makes sense to the user.
                        autoTransferFocus(false);
                    ComponentPeer peer = this.peer;
                    if (peer != null) {
                        peer.disable();
                        if (visible) {
                            updateCursorImmediately();
                if (accessibleContext != null) {
                    accessibleContext.firePropertyChange(
                        AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
                        null, AccessibleState.ENABLED);
        }The main difference appears to be with the KeyboardFocusManager. So instead of using a toolbar, I changed it to a JPanel (so the buttons are focusable). I then notice the same lag when I try to tab between the two buttons. So the problem is with the focus manager, not the setEnabled() method.

  • 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

  • Event Handling in Fullscreen Exclusive Mode???????

    WIndows XP SP2
    ATI 8500 All-In-Wonder
    JDK 1.6
    800x600 32dpi 200 refresh
    1-6 buffer strategy.
    the graphic rendering thread DOESN'T sleep.
    Here's my problem. I have a bad trade off. In fullscreen exclusive mode my animation runs <30 fps and jerks when rendering. i.e. stop and go movement (not flickering/jittering just hesitant motion) when the animation is running. I solved this problem by raising the thread priority of the rendering (7-8). . . this resulted in latency/no activity for my input events both key and mouse. For instance closing the program alt-f4 will arbitrarily fail or be successful when the thread priority is raised above 6.
    How does one accomplish a >30 fps and Instant event handling simultaneously in Fullscreen Exclusive Mode?
    Is there a way to raise thread priority for event handling?
    Ultimately I want to be able to perform my animations and handle key and mouse input events without having a visible 'hiccups' on the screen.
    Much Appreciated!

    If I remember correctly the processor is a 1.4(or)6ghz AMD Duron
    Total = 1048048kb
    Available = 106084kb
    Sys Cache = 211788kb
    PF Usage = 1.01 GB
    I solved some of the problem after posting this thread. . . .
    I inserted a thread.sleep(1) and my alt-f4 operation worked unhindered with the elevated thread priority.
    I haven't tested it with mouse event or any other key event but at the moment it looks I may have solved the problem.
    If so, my next question will be is there a way to reduce the amount of cpu power needed to run the program.
    I'm afraid that the other classes that I'm adding will actually become even more process consuming than the actually rendering thread.
    public class RenderScreen extends Thread
      // Screen Rendering status code
      protected final static int RUNNING = 0,
                                 PAUSED = -1;
      // frames per second and process time counters
      protected long now = 0, fps = 0, fpsCount = 0, cycTime = 0;
      // thread status
      protected int status = 0;
      protected Screen screen;
      public void setStatus(int i){ status = i; };
      public void setTarget(Screen screen){ this.screen=screen; };
      public void run()
        setName("Screen Render");
        screen.createBufferStrategy(1);
        screen.strategy = screen.getBufferStrategy();
        for(;;)
          if(status == RUNNING)
            now = System.currentTimeMillis();
            while(System.currentTimeMillis() <= now+1000)
              // call system processes
              // fps increment / repaint interface
              fpsCount++;
              screen.renderView();
              try { Thread.sleep(1);}catch(InterruptedException ie){ ie.printStackTrace(); }
            fps = fpsCount;
            cycTime = System.currentTimeMillis() - (now + 1000);
            fpsCount=0;
      public RenderScreen(){};
      public RenderScreen(Screen screen){ this.screen=screen; };
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Screen extends Window
      BufferedImage image = new BufferedImage(800,600,BufferedImage.TYPE_INT_RGB);
      Graphics2D gdd = image.createGraphics();
      MediaTracker tracker = new MediaTracker(this);
      Image bground = getToolkit().getImage("MajorityRule.jpg"),
            bawl = getToolkit().getImage("bawl.gif");
      RenderScreen rScreen = new RenderScreen(this);
      BufferStrategy strategy;
      Graphics g;
      Rectangle rect = new Rectangle(400,0,150,150);
      //Game game = new Game();
      public void renderView()
        g = strategy.getDrawGraphics();
        //--------- Game Procedures [start]
        gdd.drawImage(bground,0,0,this);
        gdd.drawString("fps: ["+rScreen.fps+"] Cycle Time: ["+rScreen.cycTime+"]",0,10);
        //--------- Game Procedures [end]
        //---------test
        gdd.drawImage(bawl,rect.x,rect.y,rect.width,rect.height,this);
        rect.translate(0,1);
        g.drawImage(image,0,0,this);
        //g.dispose();
        strategy.show();
      public Screen(JFrame frame)
        super(frame);
        try
          tracker.addImage(bground,0);
          tracker.addImage(bawl,1);
          tracker.waitForAll();
        catch(InterruptedException ie){ ie.printStackTrace(); }
        setBackground(Color.black);
        setForeground(Color.white);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MajorityRule extends JFrame
      // Graphic System Handlers
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      GraphicsDevice gd = ge.getDefaultScreenDevice();
      GraphicsConfiguration gc = gd.getDefaultConfiguration();
      Screen screen = new Screen(this);
      Paper paper = new Paper();
      public void windowed()
        paper.setSize(getWidth(),getHeight());
        getContentPane().add(paper);
        setResizable(false);
        setVisible(true);
      public void fullscreen()
        DisplayMode dMode = new DisplayMode(800,600,32,200);
        screen.setBounds(0,0,800,600);
        if (gd.isFullScreenSupported()) gd.setFullScreenWindow(screen);
        if (gd.isDisplayChangeSupported()){ gd.setDisplayMode(dMode); };
        screen.setIgnoreRepaint(true);
        screen.setVisible(true);
        screen.rScreen.setPriority(Thread.MAX_PRIORITY);
        screen.rScreen.start();
        screen.requestFocus();
      public MajorityRule(String args[])
        setTitle("Majority Rule [Testing Block]");
        setBounds(0,0,410,360);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        getContentPane().setLayout(null);
        if (args.length > 0 && args[0].equals("-window")) windowed();
        else fullscreen();
      public static void main(String args[])
        new MajorityRule(args);
    };

  • How to add event handling for a menu?

    hi,
    I have created a menu and few mneu items.
    for eachmenu itme , i did event handling and it is workign fine.
    it was like this
    menuItem = new JMenuItem("Exit",KeyEvent.VK_X);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK));
    menuItem.addActionListener(this);
    menu.add(menuItem);
         public void actionPerformed(ActionEvent e)
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Action event detected. Event source: " + source.getText();
    System.out.println(s);     
    public void itemStateChanged(ItemEvent e)
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Item event detected. Event source: " + source.getText();
    System.out.println(s);
    now int he second menu i don't have any menu item and i want to do the event handling for the menu itself. any ideas how to do it. following is the code for the menu
    //Build the second menu.
    menu2 = new JMenu("Options");
    menu2.setMnemonic(KeyEvent.VK_O);
    menuBar.add(menu2);
    menu2.addActionListener(this);     //this does nto work

    You were on the right track. However, selecting a menu is different from selecting a menu item. MenuItem chucks an ActionEvent and Menu will send an ItemEvent.
    If you pile all action output to one actionPerformed method then be careful of your assumptions on what the source type will be. If by any chance the Menu has sent an ActinoEvent then your code will have caused a ClassCastException.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MenuTest implements ActionListener, ItemListener {
        JMenuItem menuItem;
        JMenu menu1, menu2;
        JMenuBar menubar;
        JFrame frame;
        public MenuTest() {
            frame = new JFrame("MenuTest");
            frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
            menubar = new JMenuBar();
            frame.setJMenuBar(menubar);
            menu1 = new JMenu("File");
            menu1.setMnemonic(KeyEvent.VK_F);
            menuItem = new JMenuItem("Exit",KeyEvent.VK_X);
            menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK));
            menuItem.addActionListener(this);
            menu1.addItemListener(this);
            menu1.add(menuItem);
            menubar.add(menu1);
            //Build the second menu.
            menu2 = new JMenu("Options");
            menu2.setMnemonic(KeyEvent.VK_O);
            menu2.addActionListener(this); //this does not work
            menu2.addItemListener(this); // use this instead
            menubar.add(menu2);
            JPanel panel = new JPanel();
            panel.setPreferredSize(new Dimension(100,100));
            frame.getContentPane().add(panel);
            frame.pack();
            frame.show();
        public void actionPerformed(ActionEvent e)
            String s = "Action event detected. Event source: " + e.getSource();
            System.out.println(s);
        public void itemStateChanged(ItemEvent e)
            String s = "Item event detected. Event source: " + e.getSource();
            System.out.println(s);
        public static void main(String[] args) {
            new MenuTest();
    }

  • Help event handling

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class DemoWindow extends JFrame
         private final int WIDTH = 200, HEIGHT = 200;
         public DemoWindow() {
              //set title
              setTitle( "Event-Handling Demostration" );
              //get screen size
              Dimension d = this.getToolkit().getScreenSize();
              //1. if u want the fram to fill the whole screen use this code
              setLocation( 0, 0 );   //may not need because it's default
              setSize( d.width, d.height );
              //2. if u have a custom frame size use this code to
              //   dynamically center it (assume the given size at top)
              setSize( WIDTH, HEIGHT );
              setLocation( (d.width-this.getWidth()) / 2,
              (d.height-this.getHeight())/ 2 );
              //to end program when frame is closed (using anynomus inner class)
              addWindowListener( new WindowAdapter() {
                   public void windowClosing( WindowEvent e ) {
                        System.exit( 0 );
                        }); //end of inner class
                        public static void main( String[] args ) {
                             DemoWindow test = new DemoWindow();
                             test.setVisible( true );   }} //end of DemoWindow classWhen the program starts, the Demo window will fill � the area of the screen, and the center of the
    window will be at the center of the screen. This sizing and positioning will be based on the current
    screen display mode, not on hard-coded constants. The window title will be "Event-Handling
    Demonstration". When the window is closed, the program will end.
    The DemoPanel class will handle keyboard events using an inner class or classes. The
    isFocusTraversable method will be used to allow the DemoPanel to obtain keyboard focus.
    DemoPanel will collect from the keyboard all characters that are not action keys. Each time the Enter
    key is pressed, DemoPanel will set the title of the Demo window equal to the characters collected since
    the last time the Enter key was pressed, not including the Enter key. If the characters entered are an
    integer number greater than 0, DemoPanel will set the current drawing square size (see below) equal to
    this number. To set the square size, use a code structure similar to the following, where str is the
    String of collected characters:
    try {
    squareSize = Integer.parseInt(str);
    } catch (NumberFormatException xcp) {};
    how do i do the second part

    help

  • Event Handling Help needed please.

    Hi,
    I am writing a program to simulate a supermarket checkout. I have done the GUI and now i am trying to do the event handling. I have come up against a problem.
    I have a JCombobox called prodList and i have added an string array to it called prods . I have also created 2 more arrays with numbers in them.
    I want to write the code for if an item is selected from the combo box that the name from the array is shown in a textfield tf1, and also the price and stock no which correspond to the seclected item (both initialised in the other arrays) are also added to the textfield tf1.
    I have started writng the code but i am really stuck. Could someone please help me with this please. The code i have done so far is as follows(just the event handling code shown)
              public void ItemStateChange(ItemEvent ie){
              if(ie.getItemSelected()== prodList)
                   changeOutput();
              public void changeOutput()
                   if(ItemSelected ==0)
                        tf1.setText("You have selected" +a +b +c);
         }

    Do you say this because i missed the d of ItemStateChanged ?
    I have amended that but still i am getting the same errors class or enum expected. 4 of them relating to the itemStateChanged method.
    i will post my whole code if it helps
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Observer;  //new
    import java.util.Observable;//new
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.border.TitledBorder;
    public class MySuperMktPro
         public MySuperMktPro()
              CheckoutView Check1 = new CheckoutView(1,0,0);
              CheckoutView Check2 = new CheckoutView(2,300,0);
              CheckoutView Check3 = new CheckoutView(3,600,0);
              CheckoutView Check4 = new CheckoutView(4,0,350);
              CheckoutView Check5 = new CheckoutView(5,600,350);
              OfficeView off111 = new OfficeView();
        public static void main(String[] args) {
             // TODO, add your application code
             System.out.println("Starting My Supermarket Project...");
             MySuperMktPro startup = new MySuperMktPro();
        class CheckoutView implements ItemListener , ActionListener
        private OfficeView off1;
         private JFrame chk1;
         private Container cont1;
         private Dimension screensize,tempDim;
         private JPanel pan1,pan2,pan3,pan4,pan5;
         private JButton buyBut,prodCode;
         private JButton purchase,cashBack,manual,remove,disCo;
         private JButton but1,but2,finaLi1,but4,but5,but6;
         private JTextArea tArea1,tArea2;
         private JTextField tf1,tf2,tf3,list2;
         private JComboBox prodList;
         private JLabel lab1,lab2,lab3,lab4,lab5,lab6,lab7;
         private int checkoutID; //New private int for all methods of this class
         private int passedX,passedY;
         private String prods[];
         private JButton rb1,rb2,rb3,rb4;
         private double price[];
         private int code[];
         public CheckoutView(int passedInteger,int passedX,int passedY)
              checkoutID = passedInteger; //Store the int passed into the method
            this.passedX = passedX;
            this.passedY = passedY;
              drawCheckoutGui();
         public void drawCheckoutGui()
              prods= new String[20];
              prods[0] = "Beans";
              prods[1] = "Eggs";
              prods[2] = "bread";
              prods[3] = "Jam";
              prods[4] = "Butter";
              prods[5] = "Cream";
              prods[6] = "Sugar";
              prods[7] = "Peas";
              prods[8] = "Milk";
              prods[9] = "Bacon";
              prods[10] = "Spaghetti";
              prods[11] = "Corn Flakes";
              prods[12] = "Carrots";
              prods[13] = "Oranges";
              prods[14] = "Bananas";
              prods[15] = "Snickers";
              prods[16] = "Wine";
              prods[17] = "Beer";
              prods[18] = "Lager";
              prods[19] = "Cheese";
              for(i=0; i<prods.length;i++);
              code = new int [20];
              code[0] = 1;
              code[1] = 2;
              code[2] = 3;
              code[3] = 4;
              code[4] = 5;
              code[5] = 6;
              code[6] = 7;
              code[7] = 8;
              code[8] = 9;
              code[9] = 10;
              code[10] = 11;
              code[11] = 12;
              code[12] = 13;
              code[13] = 14;
              code[14] = 15;
              code[15] = 16;
              code[16] = 17;
              code[17] = 18;
              code[18] = 19;
              code[19] = 20;
              for(b=0; b<code.length; b++);
              price = new double [20];
              price[0] = 0.65;
              price[1] = 0.84;
              price[2] = 0.98;
              price[3] = 0.75;
              price[4] = 0.45;
              price[5] = 0.65;
              price[6] = 1.78;
              price[7] = 1.14;
              price[8] = 0.98;
              price[9] = 0.99;
              price[10] = 0.98;
              price[11] = 0.65;
              price[12] = 1.69;
              price[13] = 2.99;
              price[14] = 0.99;
              price[15] = 2.68;
              price[16] = 0.89;
              price[17] = 5.99;
              price[18] = 1.54;
              price[19] = 2.99;
              for(c=0; c<code.length; c++);
              screensize = Toolkit.getDefaultToolkit().getScreenSize();
              chk1 = new JFrame();
              chk1.setTitle("Checkout #" + checkoutID); //Use the new stored int
              chk1.setSize(300,350);
              chk1.setLocation(passedX,passedY);
              chk1.setLayout(new GridLayout(5,1));
              //chk1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              cont1 = chk1.getContentPane();
              //chk1.setLayout(new BorderLayout());
                 pan1 = new JPanel();
                 pan2 = new JPanel();
              pan3 = new JPanel();
              pan4 = new JPanel();
              pan5 = new JPanel();
              //panel 1
              pan1.setLayout(new FlowLayout());
              pan1.setBackground(Color.black);          
              prodList = new JComboBox(prods);
              prodList.setMaximumRowCount(2);
              prodList.addItemListener(this);
              but1 = new JButton("Buy");
              but1.addActionListener(this);
              lab1 = new JLabel("Products");
              lab1.setForeground(Color.white);
              lab1.setBorder(BorderFactory.createLineBorder(Color.white));
              pan1.add(lab1);
              pan1.add(prodList);          
              pan1.add(but1);
              //panel 2
              pan2 = new JPanel();
              pan2.setLayout(new BorderLayout());
              pan2.setBackground(Color.black);
              lab3 = new JLabel("                                Enter Product Code");
              lab3.setForeground(Color.white);
              tArea2 = new JTextArea(8,10);
              tArea2.setBorder(BorderFactory.createLineBorder(Color.white));
              lab5 = new JLabel("  Tesco's   ");
              lab5.setForeground(Color.white);
              lab5.setBorder(BorderFactory.createLineBorder(Color.white));
              lab6 = new JLabel("Checkout");
              lab6.setForeground(Color.white);
              lab6.setBorder(BorderFactory.createLineBorder(Color.white));
              lab7 = new JLabel("You  selected                      ");
              lab7.setForeground(Color.cyan);
              //lab7.setBorder(BorderFactory.createLineBorder(Color.white));
              pan2.add(lab7,"North");
              pan2.add(lab6,"East");
              pan2.add(tArea2,"Center");
              pan2.add(lab5,"West");
              pan2.add(lab3,"South");
              //panel 3
              pan3 = new JPanel();
              pan3.setLayout(new FlowLayout());
              pan3.setBackground(Color.black);
              manual = new JButton("Manual");
              manual.addActionListener(this);
              manual.setBorder(BorderFactory.createLineBorder(Color.white));
              remove = new JButton("Remove");
              remove.addActionListener(this);
              remove.setBorder(BorderFactory.createLineBorder(Color.white));
              tf1 = new JTextField(5);
              pan3.add(manual);
              pan3.add(tf1);
              pan3.add(remove);
              //panel 4
              pan4 = new JPanel();
              pan4.setLayout(new FlowLayout());
              pan4.setBackground(Color.black);
              finaLi1 = new JButton("Finalise");
         //     finaLi1.addActionListener(this);
              cashBack = new JButton("Cashback");
              JTextField list2 = new JTextField(5);
              but4 = new JButton(" Sum Total");
              but4.addActionListener(this);
              but4.setBorder(BorderFactory.createLineBorder(Color.white));
              cashBack.setBorder(BorderFactory.createLineBorder(Color.white));
              pan4.add(cashBack);
              pan4.add(list2);
              pan4.add(but4);
              //panel 5
              pan5 = new JPanel();
              pan5.setLayout(new GridLayout(2,3));
              pan5.setBackground(Color.black);
              disCo = new JButton("Discount");
              disCo.addActionListener(this);
              disCo.setBorder(BorderFactory.createLineBorder(Color.black));
              but6 = new JButton("Finalise");
              but6.addActionListener(this);
              but6.setBorder(BorderFactory.createLineBorder(Color.black));
              rb1 = new JButton("Cash");
              rb1.addActionListener(this);
              rb1.setBorder(BorderFactory.createLineBorder(Color.black));
              rb2 = new JButton("Card");
              rb2.addActionListener(this);
              rb2.setBorder(BorderFactory.createLineBorder(Color.black));
              rb3 = new JButton("Cheque");
              rb3.addActionListener(this);
              rb3.setBorder(BorderFactory.createLineBorder(Color.black));
              rb4 = new JButton("Voucher");
              rb4.addActionListener(this);
              rb4.setBorder(BorderFactory.createLineBorder(Color.black));
              pan5.add(disCo);
              pan5.add(but6);
              pan5.add(rb1);
              pan5.add(rb2);
              pan5.add(rb3);
              pan5.add(rb4);
              //add the panels to the container        
              cont1.add(pan1);
              cont1.add(pan4);     
              cont1.add(pan2);
              cont1.add(pan3);          
              cont1.add(pan5);          
              chk1.setContentPane(cont1);
              chk1.setVisible(true);     
    class OfficeView
         private OfficeView off111;
         private JFrame offMod1;
         private JPanel pane1;
         private JButton refill;
         private Container cont11;
         private Dimension screensize;
         private JTextField tf11,tf12;
         public OfficeView()
              drawOfficeGUI();
         public void drawOfficeGUI()
              screensize = Toolkit.getDefaultToolkit().getScreenSize();
              offMod1 = new JFrame("Office Control");
              int frameWidth = 300;
              int frameHeight = 250;
              offMod1.setSize(frameWidth,frameHeight);
              offMod1.setLocation(300,350);
              offMod1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              cont11 = offMod1.getContentPane();
              pane1 = new JPanel();
              pane1.setBackground(Color.cyan);
              refill = new JButton("Refill");
              tf11 = new JTextField(25);
              tf12 = new JTextField(25);
              pane1.add(tf11);
              pane1.add(refill);
              pane1.add(tf12);
              cont11.add(pane1);
              offMod1.setContentPane(cont11);
              offMod1.setVisible(true);
              public void ItemStateChanged(ItemEvent ie)
                        if(ie.getItemSelected()== prodList)
                                  changeOutput();
              public void changeOutput()
                        if(ItemSelected ==0)
                                  tf1.setText("You have selected", +a +b +c);
                   }Message was edited by:
    fowlergod09

  • GUI event handling problems appear in 1.4.1 vs. 1.3.1?

    Hi,
    Has anyone else experienced strange event handling problems when migrating from 1.3.1 to 1.4.1? My GUI applications that make use of Swing's AbstractTableModel suddenly don't track mouse and selection events quickly anymore. Formerly zippy tables are now very unresponsive to user interactions.
    I've run the code through JProbe under both 1.3 and 1.4 and see no differences in the profiles, yet the 1.4.1 version is virtually unusable. I had hoped that JProbe would show me that some low-level event-handling related or drawing method was getting wailed on in 1.4, but that was not the case.
    My only guess is that the existing installation of 1.3.1 is interfering with the 1.4.1 installation is some way. Any thoughts on that before I trash the 1.3.1 installation (which I'm slightly reluctant to do)?
    My platform is Windows XP Pro on a 2GHz P4 with 1GB RAM.
    Here's my test case:
    import javax.swing.table.AbstractTableModel;
    import javax.swing.*;
    import java.awt.*;
    public class VerySimpleTableModel extends AbstractTableModel
    private int d_rows = 0;
    private int d_cols = 0;
    private String[][] d_data = null;
    public VerySimpleTableModel(int rows,int cols)
    System.err.println("Creating table of size [" + rows + "," + cols +
    d_rows = rows;
    d_cols = cols;
    d_data = new String[d_rows][d_cols];
    int r = 0;
    while (r < d_rows){
    int c = 0;
    while (c < d_cols){
    d_data[r][c] = new String("[" + r + "," + c + "]");
    c++;
    r++;
    System.err.println("Done.");
    public int getRowCount()
    return d_rows;
    public int getColumnCount()
    return d_cols;
    public Object getValueAt(int rowIndex, int columnIndex)
    return d_data[rowIndex][columnIndex];
    public static void main(String[] args)
    System.err.println( "1.4..." );
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    Dimension size = new Dimension(500,500);
    panel.setMinimumSize(size);
    panel.setMaximumSize(size);
    JTable table = new JTable(new VerySimpleTableModel(40,5));
    panel.add(table);
    window.getContentPane().add(panel);
    window.setSize(new Dimension(600,800));
    window.validate();
    window.setVisible(true);
    Thanks in advance!!
    - Dean

    Hi,
    I've fixed the problem by upgrading to 1.4.1_02. I was on 1.4.1_01.
    I did further narrow down the symptoms more. It seemed the further the distance from the previous mouse click, the longer it would take for the table row to highlight. So, clicking on row 1, then 2, was much faster than clicking on row 1, then row 40.
    If no one else has seen this problem -- good! I wouldn't wish the tremendous waste of time I've had on anyone!
    - Dean

  • Beginners Questions about Multiple JPanels in JFrame and event handling

    I am a newbie with SWING, and even a newerbie in Event Handling. So here goes.
    I am writing a maze program. I am placing a maze JPanel (MazePanel) at the center of a JFrame, and a JPanel of buttons (ButtonPanel) on the SOUTH pane. I want the buttons to be able to re-randomize the maze, solve the maze, and also ouput statistics (for percolation theory purposes). I have the backbone all done already, I am just creating the GUI now. I am just figuring out EventHandlers and such through the tutorials, but I have a question. I am adding an ActionListener to the buttons which are on the ButtonPanel which are on JFrame (SOUTH) Panel. But who do I make the ActionListener--Basically the one doing the work when the button is pressed. Do I make the JFrame the ActionListener or the MazePanel the ActionListener. I need something which has access to the maze data (the backbone), and which can call the Maze.randomize() function. I'm trying to make a good design and not just slop too.
    Also I was wondering if I do this
    JButton.addActionListener(MazePanel), and lets say public MazePanel implments ActionListenerdoesn't adding this whole big object to another object (namely the button actionlistener) seem really inefficient? And how does something that is nested in a JPanel on JFrame x get information from something nested in another JPanel on a JFrame x.
    Basically how is the Buttons going to talk to the maze when the maze is so far away?

    I'm not an expert, but here's what I'd do....
    You already have your business logic (the Maze classes), you said. I'm assuming you have some kind of public interface to this business logic. I would create a new class like "MazeGui" that extends JFrame, and then create the GUI using this class. Add buttons and panels as needed to get it to look the way you want. Then for each button that does a specific thing, add an anonymous ActionListener class to it and put whatever code you need inside the ActionListener that accesses the business logic classes and does what it needs to.
    This is the idea, though my code is totally unchecked and won't compile:
    import deadseasquirrels.mazestuff.*;
    public class MazeGui extends JFrame {
      JPanel buttonPanel = new JPanel();
      JPanel mazePanel = new JPanel();
      JButton randomizeB = new JButton();
      JButton solveB = new JButton();
      JButton statsB = new JButton();
      // create instanc(es) of your Maze business logic class(es)
      myMaze = new MazeClass();
      // add the components to the MazeGui content pane
      Component cp = getContentPane();
      cp.add(); // this doesn't do anything, but in your code you'd add
                // all of your components to the MazeGui's contentpane
      randomizeB.addActionListener(new ActionListener {
        void actionPerformed() {
          Maze newMaze = myMaze.getRandomMazeLayout();
          mazePanel.setContents(newMaze); // this is not a real method!
                                          // it's just to give you the idea
                                          // of how to manipulate the JPanel
                                          // representing your Maze diagram,
                                          // you will probably be changing a
                                          // subcomponent of the JPanel
      solveB.addActionListener(new ActionListener {
        void actionPerformed() {
          Solution mySolution = myMaze.getSolution();
          mazePanel.setContents(mySolution); // again, this is not a real
                                             // method but it shows you how
                                             // the ActionListener can
                                             // access your GUI
      // repeat with any other buttons you need
      public static void main(String[] args) {
        MazeGui mg = new MazeGui();
        mg.setVisible(true);
        // etc...
    }

  • New window in event handling

    hi to all
    i m beginner in java programming and i want to do event handling on mouse click. i have a button and i want if i click that button a new window open
    can anyone help me

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ActionEvents implements ActionListener
        JDialog dialog;
        public ActionEvents(JFrame f)
            dialog = new JDialog(f, "dialog");
            dialog.getContentPane().add(new JLabel("hello world", JLabel.CENTER));
            dialog.setSize(200,100);
            dialog.setLocation(425,200);
        public void actionPerformed(ActionEvent e)
            if(!dialog.isVisible())
                dialog.setVisible(true);
            else
                dialog.toFront();
        private JPanel getPanel()
            JButton button = new JButton("open dialog");
            button.addActionListener(this);
            JPanel panel = new JPanel();
            panel.add(button);
            return panel;
        public static void main(String[] args)
            JFrame f = new JFrame();
            ActionEvents ae = new ActionEvents(f);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(ae.getPanel(), "North");
            f.setSize(200,100);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • How to set up a label control from custom event handler?

    Hi,
    Below I try to describe my problem:
    I have a single instance of MyClass (I use Cairngorm framework), with ArrayCollection as a variable, in which I would like to keep a couple addresses from database.
    Additionaly  I created a custom components with a list of people retrieved from database, with eventhandler  for a doubleclick event. After I doubleclick on some person, I create a custom event and dispatch it. In command class connected with this event I connect to the database and get full data about this person and a set of her addresses. This set of addresses I placed into ArrayCollection in my model variable. And now I have a problem, because one of this address (the birth place) I would like to display below the list with persons, in a Panel with a couple of label control, but .... I can't to bind label control to my model.addresses[???] because I don't know if this doubleclicked person has this birth address at all?
    I wonder if it is possible to set up label control in my custom components in time when I'm receiving the data from database in my custom event handler???
    One of the way to achieve this is to define a string var in my model and placed this special address in it, and then the label control to this variable, for instance {model.birthplace}, but this is only needed for a moment, I don't want to keep this address in extra variable in model, because I have already it in my ArrayCollection in model, so it would be a duplicate.
    I hope that you could understand me and my english :-)
    Best regards

    Looks like I migh not be a novice swing programmer for long then.

Maybe you are looking for