Professional Documents
Culture Documents
6 Java Swing
6 Java Swing
* AWT:
* Swing:
* import java.awt.*
* import javax.swing.*
J2sdk/demo/jfc/SwingSet2
1. 2.
Create it
* * *
Instantiate object: b = new JButton(press me); Properties: Methods: b.text = press me; b.setText(press me); [avoided in java]
Configure it
3.
4.
Add it
* *
Listen to it
JButton
From Wikipedia
GUI
Internal structure
JFrame
JPanel containers
JFrame
JPanel
JButton
JButton
JLabel
JLabel
1. 2. 3. 4. 5.
Create it
Configure it
Add children (if container) Add to parent (if not JFrame)
order important
Listen to it
* Create:
* Frame * Panel * Components * Listeners
Listener
JLabel
JButton
* Add:
(bottom up)
JPanel
JFrame
JFrame f = new JFrame(title); JPanel p = new JPanel( ); JButton b = new JButton(press me); p.add(b); f.setContentPane(p); f.show(); // add button to panel // add panel to frame
press me
import javax.swing.*;
class hello { public static void main(String[] args){ JFrame f = new JFrame(title); JPanel p = new JPanel(); JButton b = new JButton(press me);
p.add(b); f.setContentPane(p); f.show(); } } // add button to panel // add panel to frame
press me
null
FlowLayout
GridLayout
BorderLayout n
CardLayout
GridBagLayout
c s
One at a time
JButton
JButton
JButton
JTextArea
JButton
JPanel: FlowLayout
JTextArea
JFrame f = new JFrame(title); JPanel p = new JPanel( ); JButton b = new JButton(press me); b.setBounds(new Rectangle(10,10, 100,50)); p.setLayout(null); p.add(b); f.setContentPane(p);
press me
// x,y layout
p.add(b2);
f.setContentPane(p);
press me
then me