11 GUI
Event¶
Change in the state of an object
generated by userโs interaction with the GUI (graphical user interface), such as
- mouse movements
- mouse clicks
- pressing keys
Event Handling¶
control what happens if an event occurs
Delegation Event Model¶
UI and event logic are separate
Source¶
object on which event occurs
eg: buttons
Listener/Handler¶
object that
- waits for event to occur
- generates response for the event
eg: mouse click
listener should be registered with the source
Important events and listeners¶
java.util
java.awt
java.awt.event
Event Classes | Interface | Generated when |
---|---|---|
ActionEvent | ActionListener | - button press - menu-item selected - list-item is double clicked |
MouseEvent | MouseListener | - mouse dragged, moved, pressed, released - enter/exit a component |
KeyEvent | KeyListener | keyboard input |
ItemEvent | ItemListener | checkbox/list item is clicked |
TextEvent | TextListener | textarea/textfield edited |
MouseWheelEvent | MouseWheelListener | mousewheel moved |
WindowEvent | WindowListener | window activated, deactivated, opened, closed |
ComponentEvent | ComponentEventListener | component hidden |
ContainerEvent | ContainerListener | |
AdjustmentEvent | AdjustmentListener | |
FocusEvent | FocusListener |
Swing¶
part of JFC(Java Foundation Classes)
import javax.swing
swing classes all start like J...
We are using Swing Library, cuz
- Swing is for cross-platform applications; AWT is only for windows applications
- Swing is ligher than AWT
graph TB
Object --> Component --> Container & JComponent
Container --> Window & Panel
Window --> JFrame & Dialog
Panel --> Applet
JComponent --> JLabel & JButton & x[many more...]
\[ \color{hotpink} \fbox{$ \underset{ \color{orange} \fbox{$ \underset{ \color{orange} \fbox{Components} }{Panel} $}} {\text{Frame}}$} \]
Containers¶
Top Level | Lightweight | |
---|---|---|
Weight | heavy | light |
Dependence | independent | requires top level |
eg | JFrame, JDialog, JApplet | JPanel |
IDK¶
There are 2 ways
- instantiate
JFrame
class - extend
JFrame
class
import java.awt.*;
import java.swing.*;
class GUI implements ActionListener
{
GUI()
{
JFrame f = new JFrame();
JLabel l = new JLabel("Blah Blah");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JTextField tf = new JTextField();
tf.setText("Blah");
tf.setEditable(false);
JButton btn = new JButton("Click me");
btn.addActionListener(this);
JCheckBox jc = new JCheckBox();
jc.addActionListener(this);
ButtonGroup bg = new ButtonGroup();
JRadioButton r1 = new JRadioButton(),
r2 = new JRadioButton(),
r3 = new JRadioButton();
bg.add(r1); bg.add(r2); bg.add(r3);
p1.add(tf); p1.add(btn);
p2.add(jc); p2.add(bg);
f.add(p1); f.add(p1);
f.add(l);
f.setLayout(new FlowLayout() ); //null
f.setSize(200, 400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(this, "message");
if( e.getSource() == btn )
{
if( jc.isSelected() )
;
if( r1.isSelected() )
;
if( r2.isSelected() )
;
}
}
}