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
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:
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
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