Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

java.awt.ActionEvent problem

  Asked By: Adelina    Date: Nov 02    Category: Java    Views: 848
  

I create an instance of an inner class that implements ActionListener
create two JButtons and register the above instance for both.

when I do a call to java.awt.ActionEvent.getSource() I dont get
expected results code is below. If I press the ok button nothing
happens which is correct. But if I press the cancel button it should
execute System.exit(0). This does not happen any suggestions?

import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.*;

public class SamsInstaller implements Observer
{
JButton okbutton;
JButton cnbutton;
JFrame installerFrame;
JPanel installPanel;
JPanel installContentPane;
InstallListener instlisnr;

public SamsInstaller()
{
}
public void update(Observable o, Object str)
{
}
public void showInstaller()
{
JFrame installerFrame = new JFrame("SAMS9 DIICOE Installer");
JPanel installContentPane = new JPanel();
JPanel installPanel = new JPanel();
JButton okbutton = new JButton("OK");
JButton cnbutton = new JButton("CANCEL");
instlisnr = new InstallListener();

okbutton.addActionListener(instlisnr);
cnbutton.addActionListener(instlisnr);

installerFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
installPanel.setLayout(new BoxLayout
(installPanel,BoxLayout.X_AXIS));
installPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("SAMS9 DIICOE Installation"),
BorderFactory.createEmptyBorder(5,5,5,5)));


installPanel.add(okbutton);
installPanel.add(cnbutton);
installContentPane.setOpaque(true);
installContentPane.add(installPanel);
installerFrame.setContentPane(installContentPane);
installerFrame.setSize(300,300);
installerFrame.setVisible(true);
}
public static void main(String[] args)
{
SamsInstaller installerInstance = new SamsInstaller();
installerInstance.showInstaller();
}

class InstallListener implements ActionListener {

public void actionPerformed(ActionEvent event) {

if (event.getSource().equals(cnbutton))
{
System.exit(0);
}
}

}

}

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Dustin Dean     Answered On: Nov 02

How about changing the actionPerformed code...

public void  actionPerformed(ActionEvent ae) {
JButton btn = (JButton) ae.getSource();

if (btn == cnbutton) {
....
} else if (btn == okbutton) {
...
}
}

 
Answer #2    Answered By: Ruairidh Anderson     Answered On: Nov 02

I fixed the issue by putting all the code  in the constructor for the
class SamsInstaller.

 
Didn't find what you were looking for? Find more on java.awt.ActionEvent problem Or get search suggestion and latest updates.




Tagged: