javax.swing
package provides several classes using to create graphical user
interfaces. The basic steps of creating and displaying an
interface are as follows:JFrame
object.
A frame component handles basic windowing functionality, for
example closing.JPanel
objects. A panel is like a window pane. It is a
container that can hold other elements. JFrame frame = new JFrame("GUITest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 300));
frame.setVisible(true);
The
JFrame constructor takes as input a String representing the title you
will see at the top of the window.java.awt
package, which preceded swing as
the Java GUI library.JFrame frame = new JFrame("GUITest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.red);
panel.setPreferredSize(new Dimension(300, 300));
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
The
setBackground method of JPanel allows you to set the color of the
background. The Color class is in the java.awt
package.JLabel label = new JLabel("Label Me");
panel.add(label);
JButton button = new JButton("Press Me");
panel.add(button);
JTextArea area = new JTextArea();
area.setPreferredSize(new Dimension(100, 100));
area.setEditable(false);
panel.add(area);
JTextField field = new JTextField();
field.setColumns(50);
panel.add(field);
JPanel panel = new JPanel();
panel.setBackground(Color.red);
panel.setPreferredSize(new Dimension(300, 300));
panel.setLayout(new BorderLayout());
JButton button = new JButton("Press Me");
panel.add(button, BorderLayout.SOUTH);
JLabel label = new JLabel("Label Me");
panel.add(label, BorderLayout.EAST);
JTextArea area = new JTextArea();
area.setPreferredSize(new Dimension(100, 100));
area.setEditable(false);
panel.add(area, BorderLayout.CENTER);
JTextField field = new JTextField();
field.setColumns(50);
panel.add(field, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setBackground(Color.red);
panel.setPreferredSize(new Dimension(300, 300));
panel.setLayout(new GridLayout(2, 2));
JButton button = new JButton("Press Me");
panel.add(button);
JLabel label = new JLabel("Label Me");
panel.add(label);
JTextArea area = new JTextArea();
area.setPreferredSize(new Dimension(100, 100));
area.setEditable(false);
panel.add(area);
JTextField field = new JTextField();
field.setColumns(50);
panel.add(field);
public class TipPanel extends JPanel {
JButton button;
public TipPanel() {
...
button = new JButton("Calculate Tip");
button.addActionListener(new ButtonListener());
...
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
//code executed when button is pressed
}
}
}
Date: 2007-09-17