Help with JButton please.
First of all, I am extremely new to JButtons. I have watched a tutorial online and saw the basics of how it works, but the example I have only displays a message in the screen and I want to use the JButton for a different function than displaying text.
I want to put an if statement INSIDE each of the 2 JButtons that pop on the screen. Short example (not actually in java, but what I am trying to do):
if (button 1 is pressed)
{
perform certain actions
}
else if (button 2 is pressed)
{
dont perform actions and go back to how it was before pressed
}
This is the simple JButton program I have made. Any help or any link to a tutorial would be HUGELY appreciated. Thank you very much.
Code:
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class Gui extends JFrame
{
private JButton reg;
private JButton custom;
//private JButton custom;
public Gui ()
{
super("The title");
setLayout(new FlowLayout());
reg = new JButton("Check");
custom = new JButton("Pass");
add(reg);
add(custom);
HandlerClass handler = new HandlerClass();
reg.addActionListener(handler);
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener
{
@Override
public void actionPerformed(ActionEvent event)
{
JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
}
}
}
Code:
import javax.swing.JFrame;
public class ButtonTester
{
public static void main(String[] args)
{
Gui go = new Gui();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(300,200);
go.setVisible(true);
}
}
Re: Help with JButton please.
You can do it two ways, either make a new listener for every button, or attach the same listener to all the buttons and check which button was pressed inside the actionPerformed. Take a look at the ActionEvent methods, I'm pretty sure the one you are using "getActionCommand()" gives you the name of the button that was clicked.