Simple Push button and handle action event example in java!
SLVIKI
9:21 PM
0
This is a simple program that has two push buttons and handles action events. for this program I've use a JFrame, two JButtons and a JLabel. When we push a button It'll tell us which button we pressed. "Up" or "Down" button.
Here is the code of the program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | // Demostrate a push button and handle action events. import java.awt.*; import java.awt.event.*; import javax.swing.*; class ButtonDemo implements ActionListener { JLabel jlab; ButtonDemo() { // Create a new JFrame container. JFrame jfrm = new JFrame("A Button Example"); // Specify FlowLayout for the layout manager. jfrm.setLayout(new FlowLayout()); // Give the frame an initial size. jfrm.setSize(220, 90); // Terminate the program when the user closes the application. jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Make two buttons. JButton jbtnUp = new JButton("Up"); JButton jbtnDown = new JButton("Down"); // Add action listeners. jbtnUp.addActionListener(this); jbtnDown.addActionListener(this); // Add the buttons to the content pane. jfrm.add(jbtnUp); jfrm.add(jbtnDown); // Create a Label. jlab = new JLabel("Press a button."); // Add the label to the frame. jfrm.add(jlab); // Display the frame. jfrm.setVisible(true); } // Handle button events. public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand().equals("Up")) jlab.setText("You pressed Up."); else jlab.setText("You pressed down."); } public static void main(String args[]) { // Create the frame on the event dispatching thread. SwingUtilities.invokeLater(new Runnable() { public void run() { new ButtonDemo(); } }); } } |
Here is the output that we get from the program.
If you have any questions regarding this program. Feel free to ask!
Enjoy!
No comments