© L.Lúcio, An example GUI in Java n Two graphic libraries in Java u AWT u Swing n Swing is more recent than AWT: u Built on top of AWT classes; u Platform independent (looks the same everywhere); u Shouldn’t mix AWT and Swing components in the same container; u Class hierarchy roughly the same (In Swing starts with “J”) n AWT tutorial: n Swing tutorial :
© L.Lúcio, All GUIs have a top-level container n In Swing: JFrame, JDialog, JApplet n In a GUI all components are structured hierarchically starting from the top-level container:
© L.Lúcio, How to make a simple “Hello World” n Extends class JFrame (could also instantiate one); n Adds a simple label component with text. import javax.swing.*; public class HelloWorld extends JFrame { public HelloWorld() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); this.getContentPane().add(label); } public static void main(String[] args) { HelloWorld test = new HelloWorld(); test.setUndecorated(false); test.pack(); test.setVisible(true); }
© L.Lúcio, Adding a grid of Buttons n Use JButton components; n Need a way of distributing the buttons in a grid-like layout: u Use the GridLayout class from AWT; import javax.swing.*; import java.awt.*; public class GridLayoutDemo extends JFrame { static final int n = 4; public GridLayoutDemo() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel= new JPanel(); GridLayout grid = new GridLayout(n, n); panel.setLayout(grid); for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++) panel.add(new JButton("0")); this.setContentPane(panel); }...
© L.Lúcio, What do the Buttons do? n For the moment nothing… n Need to associate actions to each of the buttons: u Example: each button will count the number of times it was clicked. Button Click Listener ActionPerformed n Listener classes implement the AWT interface ActionListener overriding the ActionPerformed method;
© L.Lúcio, What do the Buttons do? (2) n Declare the class as a listener:... import java.awt.event.*; public class GridLayoutDemo extends JFrame implements ActionListener{ n Associate the this object to each button as a listener for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ int k = i * n + j; JButton oneButton = new JButton("0"); oneButton.addActionListener(this); oneButton.setActionCommand(String.valueOf(k)); buttonList.add(oneButton); panel.add(oneButton); } n All the buttons are put in an ArrayList (by number)
© L.Lúcio, What do the Buttons do? (3) n Implement the ActionPerformed method: public void actionPerformed(ActionEvent e) { JButton button = (JButton)buttonList.get(Integer.parseInt(e.getActionCommand())); int previous = Integer.parseInt(button.getText()); System.out.println(previous); button.setText(String.valueOf(++previous)); } n Get the button from the list according to its command string and increment its label.