Swing GUI: Using buttons from a different classfile in ActionListener
Hello,
I'm testing out buttons and GUI, and I'm trying to figure out how to have my actionListener take buttons from a different file, if at all possible
my current code
Code :
package visualDerp;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class PressButtonWindow extends JFrame {
public JButton button1 = new JButton("Button 1");
public JButton button2 = new JButton("Button 2");
public PressButtonWindow(String title){
setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
LayoutManager layout = new FlowLayout();
setLayout(layout);
//create the button
//setMnemonic adds an ALT+paramater hotkey to the button
button1.setMnemonic('1');
button2.setMnemonic('2');
//greys out the button
//button2.setEnabled(false);
//adds the button to the GUI
add(button1);
add(button2);
//creates a listener
PressButtonListener buttonlistener = new PressButtonListener();
//ties the listener to the button
button1.addActionListener(buttonlistener);
button2.addActionListener(buttonlistener);
//adjusts window size
pack();
}
/*
* the event handler
* should print different messages for the different buttons
*/
class PressButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource() == button1){
System.out.println("You pressed button 1. Yay!");
}
else if(event.getSource() == button2){
System.out.println("You pressed button 2. Woo!");
}
}
}
}
and the main:
Code :
package visualDerp;
public class PressButtonWindowTest {
public static void main(String[] args) {
PressButtonWindow aWindow = new PressButtonWindow("Window with a button.");
aWindow.setVisible(true);
}
}
what i WOULD LIKE is a seperate file for the buttonlistener able to use the buttons in the different file, something like this
Code :
package visualDerp;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class PressButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource() == button1){
System.out.println("You pressed button 1. Yay!");
}
else if(event.getSource() == button2){
System.out.println("You pressed button 2. Woo!");
}
}
}
while button1 and button2 are declared in a seperate file
is this possible?
rg,
VikingCoder
Re: Swing GUI: Using buttons from a different classfile in ActionListener
One way is to get the actionCommand String from the actionPerformed's ActionEvent parameter, event, by calling event.getActionCommand(), and then checking if the string equalsIgnoreCase("Button 1") or equalsIgnoreCase("Button 2"). Another way is to give each Button its own ActionListener. A third way, is to have the main class give the GUI an instance of a stand-alone Control class, give the JButton's anonymous inner class ActionListeners, and have these ActionListeners call methods from the control.