Java Reference
In-Depth Information
f . setVisible( true );
}
}
class MyFrame extends JFrame
{
public MyFrame ( ) {
final JButton button = new JButton( "Press me please" );
button. addActionListener( new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
button . setText( "Thank You!" );
}
} );
add(button) ;
pack() ;
}
} First, note that no panel is created. The button is added directly to the window. It
turns out that every window has a default canvas to which one can add GUI components.
However, if we want to use the paintComponent() method to draw something, then we need
to create a JPanel . A button belongs to the JButton class (we have the letter J because
we are using Swing). As the example shows, the constructor of the JButton class takes
as input the text of the button. An empty constructor that creates a button with no text
is also available. A button is a very simple component. The only thing that can happen
in the life of a button is that it is pressed. Therefore, a button generates action events
when it is being pressed. One can register an event listener with a button by calling the
addActionListener method. When the button is pressed, the actionPerformed method
of the event listener is called. The setText method changes the text of the button. Note
that most of the GUI components that we will examine in this chapter belong to Swing.
Remember that all classes in Swing start with the letter J .
The pack method is used to automatically set the size of the window. The method
evaluates the size of the components inside the window and sets the window size accordingly.
Note that the method should be called after all the components are added to the window. Go
ahead and run the application. Note that when the window is resized, the button continues
to take the whole window.
12.2 Flow Layout
The flow layout is the simplest layout and it is the default layout for panels. The idea
of the flow layout is that the GUI components fill the container starting from the top left
corner and filling it line by line. To see how this works, let us create a very simple application
that displays three buttons that do nothing.
import java .awt . ;
import javax . swing . ;
public class Test {
public static void main(String [] args) {
MyFrame f = new MyFrame ( ) ;
f . setVisible( true );
}
 
Search WWH ::




Custom Search