JaVa
   

Using Buttons

Every Swing component (not including the top-level containers, such as JApplet and JFrame) extends the JComponent class, which means that JComponent is the base class for all Swing components. The JComponent class contains methods that are relevant to all GUI objects. Also, the Swing architecture is a hierarchical system that uses containers and components. A container is simply a component that can contain other components, and if we look at how the JComponent is derived, we can see that it itself is in fact a container.

As you can see, Swing objects are based upon the AWT (Abstract Window Toolkit) classes, which was Swing's predecessor. To add GUI components, we can simply call the add method of the top-level container's content pane once we have actually created the objects by calling the constructor method and set up the positions, etc. (for example, in an app, the top-level container is the JFrame, whereas in an applet it is JApplet). The JButton is one of the most useful objects in the Swing package, but it is not a direct subclass of the JComponent class. In fact, it is a subclass of the AbstractButton class, which is a more generic representation of a button that is then extended to create the JButton class. Note that the AbstractButton class first extends the JComponent class though. The JButton component allows us to perform an action if the user clicks on it by implementing an ActionListener. Basically, this works by making our class handle events that are sent via the Event Dispatch Thread, informing us that the button has been clicked. When we implement the ActionListener, we override a method called actionPerformed, which is called every time an ActionEvent is dispatched via a component that has a listener associated with it. Which button was clicked can then be determined by the ActionEvent parameter, which is passed into the actionPerformed method. Let's take a look at an example now to try and make this clearer. In the example, we will create three buttons, each of which will update a JLabel (another simple GUI component that can be used to easily output static text), informing you as to which button was pressed last.

Code Listing 13-1: Using the JButton object
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonExample extends JFrame implements ActionListener
<>
 public JButtonExample()
 <>
 super("JButton Example");
 setBounds(0, 0, 300, 300);
 getContentPane().setLayout(null);
 setResizable(false);
 setDefaultCloseOperation(EXIT_ON_CLOSE);
 // Create the label...
 label = new JLabel("No button pressed");
 label.setLocation(10, 10);
 label.setSize(label.getPreferredSize());
 // Create the three buttons...
 button1 = new JButton("Button 1");
 button1.setLocation(10, 40);
 button1.setSize(button1.getPreferredSize());
 button2 = new JButton("Button 2");
 button2.setBounds(10, 80, 270, 40);
 button3 = new JButton("Button 3");
 button3.setBounds(60, 140, 160, 100);
 button3.setBackground(new Color(255, 0, 0));
 button3.setForeground(new Color(0, 255, 0));
 // Add the action listeners
 button1.addActionListener(this);
 button2.addActionListener(this);
 button3.addActionListener(this);
 // Add the objects to the content pane...
 getContentPane().add(label);
 getContentPane().add(button1);
 getContentPane().add(button2);
 getContentPane().add(button3);
 setVisible(true);
 <>
 public void actionPerformed(ActionEvent e)
 <>
 if(e.getSource() == button1)
 <>
 label.setText("Button 1 was pressed last");
 label.setSize(label.getPreferredSize());
 <>
 else if(e.getSource() == button2)
 <>
 label.setText("Button 2 was pressed last");
 label.setSize(label.getPreferredSize());
 <>
 else if(e.getSource() == button3)
 <>
 label.setText("Button 3 was pressed last");
 label.setSize(label.getPreferredSize());
 <>
 <>
 public static void main(String[] args)
 <>
 JButtonExample mainApp = new JButtonExample();
 <>
 JLabel label;
 JButton button1;
 JButton button2;
 JButton button3;
<>


Java End example

When we execute the JButton example code, we can see that it looks like the following:

Java ScreenShot
Screenshot-1: The JButton Example app

As you can see from this figure, our app shows the three buttons that we added. When we press each of the buttons, they update the JLabel above the buttons to show which button was pressed last. Let's look now at the code that we used to create the buttons. First we create a JLabel object, which is simply a component that can be used to display a string of text. We are going to use this to display which button was pressed last by the user. We create the JLabel using the following code segment:

label = new JLabel("No button pressed");
label.setLocation(10, 10);
label.setSize(label.getPreferredSize());


Note how we set the default text to be displayed in the label by passing a string to the constructor. Also notice how we call the setLocation method to set the x, y position of the label relative to its container and also the setSize method, to which we pass in the preferred size (which is obtained by calling the getPreferredSize method of the JLabel object). To create Button 1 we simply specify the text to appear on the button by passing it to the JButton constructor and then set its location and size appropriately. This can be seen in the following segment of code:

button1 = new JButton("Button 1");
button1.setLocation(10, 40);
button1.setSize(button1.getPreferredSize());


For our second button, we use the setBounds method instead of the setLocation and setSize methods to simply specify the dimensions of the button. This can be seen in the following line of code:

button2.setBounds(10, 80, 270, 40);


In this case, the top-left corner of the button will be positioned at 10, 80, and it will be 270 pixels wide and 40 pixels high. For our final button, we again call the setBounds method, but this time we also set the background color of the button to red and the text color (foreground color) to green. This is achieved with the following two lines of code:

button3.setBackground(new Color(255, 0, 0));
button3.setForeground(new Color(0, 255, 0));


Once we have all of our buttons created, we next add action listeners to each of the buttons using the addActionListener method, which is defined in the AbstractButton super class. In this particular case, the listener is our class itself (as it implements the ActionListener interface). Therefore, it is passed as a parameter to the addActionListener method. The action listener works in the same way as mouse and keyboard listeners that we used in . The action listener handles the user clicking on the button and allows us to execute code when this happens. Here is our complete actionPerformed method:

 public void actionPerformed(ActionEvent e)
 <>
 if(e.getSource() == button1)
 <>
 label.setText("Button 1 was pressed last");
 label.setSize(label.getPreferredSize());
 <>
 else if(e.getSource() == button2)
 <>
 label.setText("Button 2 was pressed last");
 label.setSize(label.getPreferredSize());
 <>
 else if(e.getSource() == button3)
 <>
 label.setText("Button 3 was pressed last");
 label.setSize(label.getPreferredSize());
 <>
 <>


Notice how we use the getSource method of the ActionEvent object, which is passed to the actionPerformed method to determine which button the user clicked. So in this example, to test if the button1 object was clicked, we use the following segment of code:

if(e.getSource() == button1)
<>
 // code to be executed when the button is clicked goes here
<>


NoteĀ 

You can, of course, as we saw in , add action listeners on the fly as follows:

button3.addActionListener(new ActionListener(
<>
 public void actionPerformed(ActionEvent e)
 <>
 System.out.println("Button 3 pressed!");
 <>
<>);
JaVa
   
Comments