programming
1 Part 2
1.1 Graphical User Interface
1.1.1 GUI components, JOptionPane
Horstman 10.1
- JComponents are added to a JFrame and positioned using a LayoutManager
- Functionality via EventListener
- JFrame methods
Most common to include:
- setTitle
- setSize
- setLocation
- setVisible
- setDefaultCloseOperation JFrame.EXITONCLOSE
- GUI components
- JButton
- JTextField
- setText
- getText
- JLabel
- Disabling comgonents
component.setEnabled(false); textfield.setEditable(false);
- Exameple:
import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class Window extends JFrame { public static void main(String[] args) { JFrame frame = new Window(); } public Window() { JFrame frame = new JFrame(); JButton button = new JButton("Click here"); JLabel label = new JLabel("HALLo!"); JTextField tf = new JTextField("text field", 10); JPanel panel = new JPanel(); panel.add(button); panel.add(label); panel.add(tf); tf.setEditable(false); frame.add(panel); frame.setSize(150, 200); frame.setTitle("An example frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
1.1.2 Layout managers
Lecture 2 Horstman 11.1 JPanel
- BorderLayout
- FlowLayout
- GridLayout
- JPanel
- within
JFrame
- methods
- setBackground
- getHeight / getWidt
panel.setLayout(new LayoutName());
- within
- FlowLayout
- default
JPanel
layout - centered, in add order, left to right
- default
- GridLayout
new GridLayout(rows, cols) //@param are ints;
- optionally
hGap
andvGap
- optionally
1.1.3 GUI events, action listeners
Horstman 10.2
- Event listeners
- event source is UI component
public class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event ) { System.out.println(event); } }
button.addActionListener(new ClickListener());
- Inner Classes
use action listeners as inner classes
public class ButtonFrame extends JFrame { //inner class class ClickListener implements ActionListener{ ... } private void CreateComponents() { ... } }
- listener classes are short
- inner classes can access instance variablest and surounding methods [useful for event handlers]