Results 1 to 2 of 2
Thread: Help with JButton please.
- 11-11-2012, 09:10 PM #1
Member
- Join Date
- Aug 2012
- Posts
- 16
- Rep Power
- 0
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.
Java 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())); } } }Java 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); } }
- 11-13-2012, 04:27 PM #2
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.
Similar Threads
-
JButton
By Proshitness in forum AWT / SwingReplies: 11Last Post: 12-07-2011, 04:25 PM -
JButton help
By kyle_maddisson in forum New To JavaReplies: 12Last Post: 11-14-2011, 08:39 AM -
ActionListener for JButton after changing Button to JButton
By ravi.joshi53 in forum Java AppletsReplies: 2Last Post: 10-07-2011, 07:35 AM -
JButton help
By ThrashingBoy in forum New To JavaReplies: 2Last Post: 01-29-2011, 12:39 PM -
Help with JButton
By geoffreybarwise in forum New To JavaReplies: 4Last Post: 05-21-2008, 10:48 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks