Solved

How do I have to add an ActionListener?

Posted on 1998-06-24
7
462 Views
Last Modified: 2008-02-01
I have a main program that invokes a JDialog.
How can I add an ActionListener to the JButtons used in the JDialog?
The main program should be the Listener and therefore implements the ActionListener interface.

In the JDialog I have accessor methods which returns the JButtons where the ActionListener should be added to.
public JButton getOk()
{
return ok;
}
public JButton getCancel()
{
return cancel;
}

In the main program I implemented the following code:
JDialog myDialog = new JDialog("MyDialog");
myDialog.getOk().addActionListener(this));
myDialog.getCancel().addActionListener(this));

public void actionPerformed(ActionEvent ae)
{
System.out.println(ae);
}

It compiles properly but clicking the JButtons takes no effect. Why? ... and what can I do?
0
Comment
Question by:dirku
  • 4
  • 3
7 Comments
 
LVL 5

Accepted Solution

by:
msmolyak earned 10 total points
Comment Utility
If your dialog is modal and you call setVisible(true) in the constructor, then after executing the line
JDialog myDialog = new JDialog("MyDialog");
the main thread stops and continues only after the dialog is closed. The solution is to make the dialog visible in the main program after registering the listeners or passing the listener class into the dialog constructor and registering the listener before making the dialog visible there.
0
 

Author Comment

by:dirku
Comment Utility
Could you provide me with some source code?
Here's my main program as well as the JDialog which is the event source. The main program is the event listener.

The following code is already running! Copy it into your IDE and compile it so you can see what I intend to do.

Since it is much to read I increased points up to 15! Okay?
Please, make changes if neccessary:

import java.awt.*;
import java.awt.event.*;

public class Main extends Frame implements ActionListener
{
      NewStockDialog nsd;
      
      public Main(String title)
      {
            nsd = new NewStockDialog(title);
            nsd.getOk().addActionListener(this);
            nsd.getCancel().addActionListener(this);
      }//end constructor
      
      public void actionPerformed(ActionEvent ae)
      {
            
            System.out.println(ae);
            if(nsd.getOk().getLabel().equals(ae.getActionCommand()))
                  System.out.println("'OK' in JDialog was clicked!");
            
      }
      //---------
      public static void main(String[] args)
      {
            Main m = new Main("NewStockDialog-Test");
            System.exit(0);
      }//end main
}//end class Main

The following source code is a litle longer just because of arranging the components with BoxLayout...

//IMPORT SECTION
import java.awt.*;
import java.awt.event.*;

import java.awt.Insets;
import java.util.Date;
import com.sun.java.swing.BoxLayout;
import com.sun.java.swing.Box;
import com.sun.java.swing.JDialog;
import com.sun.java.swing.JFrame;
import com.sun.java.swing.JComboBox;
import com.sun.java.swing.JTextField;
import com.sun.java.swing.JLabel;
import com.sun.java.swing.JButton;
import com.sun.java.swing.Icon;

import com.sun.java.swing.*;
import com.sun.java.swing.border.*;

import com.sun.java.swing.JPanel;
//end IMPORT SECTION

public class NewStockDialog extends JDialog// implements ActionListener
{
      protected ActionListener listeners = null;

      private JTextField date;
      private JTextField price;
      private JTextField numberOf;
      private JTextField charges;
      private JTextField note;
      
      private JLabel dateLabel;
      private JLabel priceLabel;
      private JLabel numberOfLabel;
      private JLabel chargesLabel;
      private JLabel noteLabel;
      
      private JComboBox portfolios;
      private JLabel portfoliosLabel;
      private JComboBox stocks;
      private JLabel stocksLabel;
      
      private JLabel functionLabel;
      private JLabel pricePerStockLabel;
      private JLabel sumLabel;

      private static JButton ok;
      private static JButton cancel;

      //Icon???
      private static Icon icon = null;
      // ---> !!! JLabel mit Icon !!! <---
//      private JComboBox portfolios;
//      private JComboBox stocks;

      private String bordertitle;
      private String currency;
      private String filler;
      private GridBagLayout gbl = new GridBagLayout();
      
      //---------------------------------------------------------------------------
      
      public NewStockDialog(String title)//, ActionListener l)
      {
            super(new JFrame(), title, true);

            ok = new JButton("Ok");
            cancel = new JButton("Abbrechen");
            //ok.addActionListener();
            //cancel.addActionListener();

            bordertitle = "Wertpapieranlage";
            currency = "DM";
            filler = " ";
            
            functionLabel = new JLabel("Das neue Wertpapier wird "+
                                                                                           "in eines Ihrer Portfolios eingetragen.");
            pricePerStockLabel = new JLabel(currency + filler + "pro Aktie");
            sumLabel = new JLabel(currency + filler + "insgesamt");
            
            portfoliosLabel = new JLabel("Portfolios");
            stocksLabel = new JLabel("Wertpapier");
            
            dateLabel = new JLabel("Kaufdatum");
            priceLabel = new JLabel("Kaufpreis");
            numberOfLabel = new JLabel("Anzahl");
            chargesLabel = new JLabel("Gebühren");
            noteLabel = new JLabel("Bemerkung");
            
            date = new JTextField(20);
            price = new JTextField(20);
            numberOf = new JTextField(20);
            charges = new JTextField(20);
            note = new JTextField(20);

      //      portfolios = new JComboBox(PMPortfolioBox.getPortfolios());
      //      for(int i=0; i<portfolios.getItemCount(); i++)
      //            System.out.println("Portfolio mit Name: " + portfolios.getItemAt(i));
            portfolios = new JComboBox();
            stocks = new JComboBox();
            //jcb_stocks = new JComboBox(PM.getAllStocks());
            
            for(int j=0; j<stocks.getItemCount(); j++)
                  System.out.println("Portfolio mit Name: " + stocks.getItemAt(j));
                        
            //------------------
            //Creating the Boxes
            //------------------
            Box box0            = new Box(BoxLayout.Y_AXIS);
            Box box1             = new Box(BoxLayout.X_AXIS);
            Box box2             = new Box(BoxLayout.X_AXIS);
            Box box3             = new Box(BoxLayout.X_AXIS);
            Box box4             = new Box(BoxLayout.X_AXIS);
            Box box5            = new Box(BoxLayout.X_AXIS);
            Box box6             = new Box(BoxLayout.X_AXIS);

            Box p1             = new Box(BoxLayout.Y_AXIS);
            Box p2             = new Box(BoxLayout.Y_AXIS);
            Box p2_1       = new Box(BoxLayout.X_AXIS);
            Box p2_2       = new Box(BoxLayout.X_AXIS);
            Box p2_3       = new Box(BoxLayout.X_AXIS);
            Box p2_4       = new Box(BoxLayout.X_AXIS);
            Box p2_5       = new Box(BoxLayout.X_AXIS);
            
            Box sepBox       = new Box(BoxLayout.X_AXIS);
            Box box2_1       = new Box(BoxLayout.X_AXIS);

            JPanel panel = new JPanel();
            TitledBorder border = new TitledBorder(bordertitle);
            border.setBorder(new EtchedBorder());
            panel.setBorder(border);
            panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
      
            box1.add(Box.createHorizontalStrut(25));
            box1.add(functionLabel);
            box1.add(Box.createGlue());

            sepBox.add(Box.createHorizontalStrut(3));
            sepBox.add(new JSeparator());

            box2_1.add(portfoliosLabel);
            box2_1.add(Box.createHorizontalStrut(30));
            box2_1.add(Box.createGlue());
            box2_1.add(portfolios);
            box2.add(Box.createHorizontalStrut(10));
            box2.add(box2_1);
            //box3:
            p1.add(Box.createVerticalStrut(5));
            p1.add(stocksLabel);
            p1.add(Box.createVerticalStrut(20));
            p1.add(dateLabel);
            p1.add(Box.createVerticalStrut(13));
            p1.add(priceLabel);
            p1.add(Box.createVerticalStrut(13));
            p1.add(numberOfLabel);
            p1.add(Box.createVerticalStrut(13));
            p1.add(chargesLabel);
            
            p2_1.add(stocks);
            p2_1.add(Box.createHorizontalStrut(20));
            p2_2.add(date);
            p2_2.add(Box.createHorizontalStrut(300));
            p2_3.add(price);
            p2_3.add(Box.createHorizontalStrut(10));
            p2_3.add(pricePerStockLabel);
            p2_3.add(Box.createHorizontalStrut(200));
            p2_3.add(Box.createGlue());
            p2_4.add(numberOf);
            p2_4.add(Box.createHorizontalStrut(300));
            p2_5.add(charges);
            p2_5.add(Box.createHorizontalStrut(10));
            p2_5.add(sumLabel);
            p2_5.add(Box.createGlue());
            p2_5.add(Box.createHorizontalStrut(200));
            p2.add(p2_1);
            p2.add(Box.createVerticalStrut(10));
            p2.add(p2_2);
            p2.add(Box.createVerticalStrut(20));
            p2.add(p2_3);
            p2.add(Box.createVerticalStrut(10));
            p2.add(p2_4);
            p2.add(Box.createVerticalStrut(10));
            p2.add(p2_5);
            panel.add(p1);
            panel.add(Box.createHorizontalStrut(30));
            panel.add(p2);
            box3.add(panel);

            box4.add(Box.createHorizontalStrut(3));
            box4.add(noteLabel);
            box4.add(Box.createGlue());
            
            box5.add(Box.createHorizontalStrut(3));
            box5.add(note);
            box5.add(Box.createGlue());
            
            box6.add(Box.createGlue());
            box6.add(ok);
            box6.add(Box.createHorizontalStrut(15));
            box6.add(cancel);

            Container dialog = getContentPane();
            dialog.setLayout(gbl);
                        
            makeComponent(dialog,box0,0,0,1.0,1.0,GridBagConstraints.REMAINDER,
                                                      GridBagConstraints.REMAINDER,GridBagConstraints.BOTH,
                                                      GridBagConstraints.CENTER,10,10,10,10);
            
            box0.add(box1);
            box0.add(Box.createVerticalStrut(10));
            box0.add(sepBox);
            box0.add(Box.createVerticalStrut(10));
            box0.add(box2);
            box0.add(Box.createVerticalStrut(10));
            box0.add(box3);
            box0.add(Box.createVerticalStrut(10));
            box0.add(box4);
            box0.add(Box.createVerticalStrut(10));
            box0.add(box5);
            box0.add(Box.createVerticalStrut(10));
            box0.add(box6);

            //setSize(400,300);
            setResizable(false);
            pack();
            show();
      }//end constructor

      //---------------------------------------------------------------------------
      //Internal methods
      //---------------------------------------------------------------------------
      
      //---------------------------------------------------------------------------
      //Accessor methods
      //----------------
      //setter methods
      //--------------
      public void setPortfolios(JComboBox portfolios)
      {
            this.portfolios = portfolios;
      }
      
      //getter methods
      //--------------
      public JComboBox getPortfolios()
      {
            return portfolios;
      }
      
      public JButton getOk()
      {
            return ok;
      }
      
      public JButton getCancel()
      {
            return cancel;
      }
      
      //---------------------------------------------------------------------------
      // The makeComponent() method is designed to create an AWT component to be
      // placed in a GridBagLayout.
      // PARAMETERS:
      // container  --> the container where the component will be placed
      // component  --> the component you want to create
      // gridx              --> the x-coord of the cell to contain the created component
      // gridy              --> the y-coord of the cell to contain the created component
      // weightx        -->
      // weighty        -->
      // gridwidth  --> how many rows the component occupies
      // gridheight --> how many columns the component occupies
  //---------------------------------------------------------------------------
      public void makeComponent(Container container, Component component, int gridx,
                                                              int gridy, double weightx, double weighty, int gridwidth,
                                                              int gridheight, int fill, int anchor, int top, int left,
                                                              int bottom, int right)
      {
            GridBagConstraints gbc = new GridBagConstraints();
                        
            gbc.insets.top = top;
            gbc.insets.left = left;
            gbc.insets.right = right;
            gbc.insets.bottom = bottom;

            gbc.gridx = gridx;
            gbc.gridy = gridy;
            gbc.weightx = weightx;
            gbc.weighty = weighty;
            gbc.gridwidth = gridwidth;            // 0 == REMAINDER; > 0 == number of rows
            gbc.gridheight = gridheight;      // 0 == REMAINDER; > 0 == number of columns
            gbc.fill = fill;
            gbc.anchor = anchor;
            gbl.setConstraints(component, gbc);
            container.add(component);
      }//end makeComponent
      
}//end class NewStockDialog

0
 
LVL 5

Expert Comment

by:msmolyak
Comment Utility
Yes, I was talking about show() method at the end of your dialog constructor. If you call it in the main program after registering the listeners the code should work.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:dirku
Comment Utility
I hope it works well grading your answer and adding a comment simultaneously!

Surely your hair stood on end (do you say so in English? I tried to translate from German!) because I didn't understand what you wanted to tell me ;-)

Now it works, but why does it not work when invoking setVisible(true) or show() from within the JDialog???
That's of much interest to me and I hope you'll answer it after grading...if possible. Otherwise: email ulrich@tembit.com
0
 
LVL 5

Expert Comment

by:msmolyak
Comment Utility
You have to understand the concept of modal dialogs. Whenever you make the modal dialog visible the thread which created it and called setVisible(true) or show() (which is a leftover from JDK 1.0) stops and does not continue until the other thread (which run the dialog) closes it by executing setVisible(false) or destroy(). Since you were making calls to add listeners after making the dialog visible they were not executed antil AFTER the dialog was closed. Thus your objective was to make sure that the listeners are registered BEFORE you show the dialog. And it does not matter where you show the dailog, in the constructor or in the main program as long as you register your listeners before that.

Hope that makes it clearer. And thanks for you concern about my hair. (We have a similar expression in Russian, so I know what you mean).

Michael
0
 

Author Comment

by:dirku
Comment Utility
I got it running! Thanks. But as it is possible after solving one problem a further one occured!!!

Please give me your email address if you want the source in a zipped file. In any case i add the code here, too. I suppose it's the same or a similar problem as I had before.

In the main applet I have a menu with -of course- some menu items. Until now I have added an ActionListener to each menu item this way:


JMenuItem item;       //declared locally

item = new JMenuItem("Ansicht");
settingsMenu.add(item);
//item.addActionListener(this);   //for trying with item declared globally in this class

item.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
                              vod = new ViewOptionsDialog("TemCash - Options view");
                              vod.getOk().addActionListener(this);
                              vod.getCancel().addActionListener(this);
                              vod.setVisible(true);

                        }
                  });

In the main applet I have implemented the ActionListener interface.
My intention was to create a particular JDialog instance only when used. So I generated such a dialog only when the particular menu item was choosen.
The problem: Because of the local ActionListener/actionPerformed method the actionPerformed method of the main applet was never reached.
Besides, whenever clicking the ok or cancel button a new instance of the dialog is generated(of course, because in the actionPerformed method the new operator is used!!!).
Deleting the local ActionListener/actionPerformed method from the menu item to handle the ActionEvent in the actionPerformed method of the main applet it results in a NullPointerException because the dialogs are generated only when they were used.

Attached you'll find a further extraction from my code but it's very long I think for reading at Ex-Ex. So if you wish give me your email address and I'll send you the code.

public class PM extends JApplet implements ActionListener
{
//The dialogs...
      private IdentificationDialog idDialog;
      private ModifyStockDialog msd;
      private NewStockDialog nsd;
      private SelectionDialog sd;
      private ViewOptionsDialog vod;

//-----------------------------------------------------------------------------      
      public void init()
      {
.
createMenus();
.
}//end init

      //----------------------------------------------------------------------------
      // The createMenus() method is designed to build the menus used in this
      // Applet. Each JMenuItem is associated with an individual ActionListener.
  //----------------------------------------------------------------------------
      private void createMenus()
      {            
            JMenuBar mb1 = new JMenuBar();
            JMenuBar mb2 = new JMenuBar();
            
            JMenu manipulationMenu = new JMenu("Edit");
            JMenu settingsMenu = new JMenu("Preferences");
            
            manipulationMenu.setToolTipText("Edit menu");
            settingsMenu.setToolTipText("Preferences menu");
            
            JMenuItem item;

            mb1.setAlignmentY(JComponent.TOP_ALIGNMENT);
            mb2.setAlignmentY(JComponent.TOP_ALIGNMENT);

            box2.add(mb1);
            box2.add(Box.createHorizontalStrut(10));
            box2.add(mb2);

            item = new JMenuItem("Add stock to portfolio");
            manipulationMenu.add(item);
            item.addActionListener(new ActionListener()
                  {
                        public void actionPerformed(ActionEvent e)
                        {
                              nsd = new NewStockDialog("TemCash - add stock");
                              nsd.getOk().addActionListener(this);
                              System.out.println("ActionListener registered with Ok-Button!");
                              nsd.getCancel().addActionListener(this);
                              System.out.println("ActionListener registered with Cancel-Button!");
                              nsd.setVisible(true);
                        }
                  });
.
}//end createMenus


//The main applet's actionPerformed method: ==> version for JMenuItem == global
//---------------------------------------------------------------------------
      public void actionPerformed(ActionEvent Ae)
      {
            System.out.println("ActionEvent recognized...:-))");
            System.out.println(Ae.getActionCommand());

            if(Ae.getActionCommand().equals(item.getLabel()))
            {
                  vod = new ViewOptionsDialog("TemCash - Options view");
                  vod.getOk().addActionListener(this);
                  vod.getCancel().addActionListener(this);
                  vod.setVisible(true);
            }
//handle ActionEvent for choosing ok button in dialog msd
            if(Ae.getActionCommand().equals(msd.getOk().getLabel()))
            {
System.out.println("Ok-Button in msd was clicked!");
                  msd.setVisible(false);
            }
.
}//end actionPerformed

//The main applet's actionPerformed method: ==> version for JMenuItem == local
//---------------------------------------------------------------------------
      public void actionPerformed(ActionEvent Ae)
      {
//To see that the ActionEvent occured at all!
            System.out.println("ActionEvent recognized...:-))");
            System.out.println(Ae.getActionCommand());
//handle ActionEvent for choosing menu item
            if(Ae.getActionCommand().equals(item.getLabel()))
            {
                  vod = new ViewOptionsDialog("TemCash - Options view");
                  vod.getOk().addActionListener(this);
                  vod.getCancel().addActionListener(this);
                  vod.setVisible(true);
            }
//handle ActionEvent for choosing ok button in msd
//this causes a NullPointerException as msd is generated just when needed
            if(Ae.getActionCommand().equals(msd.getOk().getLabel()))
            {
System.out.println("Ok-Button in msd was clicked!");
                  msd.setVisible(false);
            }
.
}//end actionPerformed

Oops! That's a very long text. Want further points? Dell me!

Dirk

0
 
LVL 5

Expert Comment

by:msmolyak
Comment Utility
Dirk, I will gladly look at this issue if you post it as a separate question. It is customary on the Experts Exchange to post only one problem per question.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now