The main differences between AWT and Swing (taken from www.pediaa.com) :
Component
AWT
Label
AWT
Container
AWT
JComponent
JLabel
JComboBox
AbstractButton
JButton
JToggleButton
JCheckBox
JRadioButton
JMenuItem
JMenu
JCheckBoxMenuItem
JMenuBar
JPanel
JToolBar
JScrollPane
JTabbedPane
JSplitPane
JTextComponent
JTextField
JTextArea
JEditorPane
JList
JTree
JTable
Window
AWT
Frame
AWT
JFrame
Dialog
AWT
JDialog
Jwindow
import javax.swing.* ;
public class Window1 {
public
static void main (String args[]){
JFrame
wd = new JFrame() ;
wd.setSize
(250, 100) ;
wd.setTitle
("graphic window") ;
wd.setVisible
(true) ;
}
}
wd.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
wd.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
// default)
wd.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
wd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Modifications on the JFrame
import javax.swing.* ;
public class MyFrame extends JFrame{
MyFrame(int x, int y, int ln, int ht){
this.setBounds(x, y, ln, ht);
this.setVisible(true);
this. setTitle ("graphic
window") ;
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import java.util.*;
public class Test1 {
public static void main(String arg[]){
Scanner in = new
Scanner(System.in);
MyFrame mf = new
MyFrame(50,80,300,250);
System.out.print("new frame
created, enter to change dimensions");
in.nextLine();
mf.setSize (350, 300) ;
System.out.print("new name:
");
String s = in.nextLine();
mf.setTitle
(s);
System.out.println("boundaries modified ");
mf.setBounds(60,45,350,220); //x, y of
the upper left corner, length, height
System.out.print("new length
");
int ln=
Integer.parseInt(in.nextLine());
System.out.print("new height
");
int height=
Integer.parseInt(in.nextLine());
mf.setSize (ln,height);
System.out.print("enter to
make invisible:");
in.nextLine();
mf.setVisible(false);
System.out.print("enter to
make visible:");
in.nextLine();
mf.setVisible(true);
System.out.print("enter to
finish program");
in.nextLine();
System.exit(1);
}
}
class MyMouse
implements MouseListener {
public
void mouseClicked (MouseEvent ev) { ..... }
public
void mousePressed (MouseEvent ev) { ..... }
public
void mouseReleased(MouseEvent ev) { ..... }
public
void mouseEntered (MouseEvent ev) { ..... }
public
void mouseExited (MouseEvent ev) { ..... }
}
Using an inner class for a listenerimport java.awt.event.*;
import javax.swing.* ;
public class MyFrame extends JFrame{
private static final long serialVersionUID = 1L;
JLabel l;
MyFrame(int x, int y, int ln, int ht){
this.setBounds(x, y, ln,
ht);
this.addMouseListener(new
MyMouse());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l=new JLabel("to show mouse
events",JLabel.CENTER);
add(l);
this.setVisible(true);
}
public class MyMouse implements MouseListener{
public void
mouseClicked(MouseEvent ev) {
int x =
ev.getX(); int y=ev.getY();
int
xabs=ev.getXOnScreen(); int yabs=ev.getYOnScreen();
l.setText("in: x= "+x+ " y="+y+" ("+xabs+","+yabs+") on screen");
if(ev.getClickCount()==2) l.setText(l.getText()+" double clicked");
}
public void mousePressed
(MouseEvent ev) {}
public void
mouseReleased(MouseEvent ev) {}
public void mouseEntered
(MouseEvent ev) {
l.setText("mouse in");
}
public void mouseExited
(MouseEvent ev) {
l.setText("mouse out");
}
}
}
public
class Test {
public static void main(String arg[]){
new
MyFrame(50,80,400,350);
}
}
Adapter
class MouseAdapter
implements
MouseListener {
public
void mouseClicked (MouseEvent ev) {}
public
void mousePressed (MouseEvent ev) {}
public
void mouseReleased(MouseEvent ev) {}
public
void mouseEntered (MouseEvent ev) {}
public
void mouseExited (MouseEvent ev) {}
}
--------------------
public class MyMouse
extends MouseAdapter
{
public
void mouseClicked(MouseEvent ev) {
System.out.println("x="+ev.getX()
+ " y="+ ev.getY());
}
public
void mouseEntered (MouseEvent ev) {
System.out.println("mouse
in");
}
public
void mouseExited (MouseEvent ev) {
System.out.println("mouse
out");
}
}
import
javax.swing.* ; public class MyFrame extends JFrame{ MyFrame(String name,int x, int y, int ln, int ht){ this.setBounds(x, y, ln, ht); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle(name); } } import javax.swing.*; public class Test { public static void main(String arg[]){ MyFrame mf = new MyFrame("ButtonOne",50,80,200,150); JButton bt1 = new JButton("butt1"); mf.add(bt1); // default Layout mf.validate(); // validate the container } } |
import
java.awt.*; import javax.swing.*; public class Test { public static void main(String arg[]){ MyFrame mf = new MyFrame("ButtonOne",50,80,200,150); mf.setLayout(new FlowLayout()); JButton bt1 = new JButton("butt1"); JButton bt2 = new JButton("butt2"); mf.add(bt1); mf.add(bt2); mf.validate(); } } |
Listener
import
javax.swing.* ; public class MyFrame extends JFrame{ MyFrame(String name,int x, int y, int ln, int ht){ this.setBounds(x, y, ln, ht); this.setVisible(true); this.setTitle(name); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } ------------------------- import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Test { static int cnt1=0,cnt2=0; public static void main(String arg[]){ MyFrame mf = new MyFrame("ButtonOne",50,80,200,150); mf.setLayout(new FlowLayout()); JButton bt1 = new JButton("butt1"); JButton bt2 = new JButton("butt2"); mf.add(bt1); mf.add(bt2); bt1.addActionListener(new Bt1()); bt2.addActionListener(new Bt2()); mf.validate(); } static class Bt1 implements ActionListener{ public void actionPerformed(ActionEvent ev){ System.out.println("butt1: "+ ++cnt1+" times clicked"); } } static class Bt2 implements ActionListener{ public void actionPerformed(ActionEvent ev){ System.out.println("butt2: "+ ++cnt2+" times clicked"); } } } |
getSource() (can be used for all components)
import
javax.swing.* ; public class MyFrame extends JFrame{ MyFrame(String name,int x, int y, int ln, int ht){ this.setBounds(x, y, ln, ht); this.setVisible(true); this.setTitle(name); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } ---------------------------------------------------------- import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Test1 { static int cnt1=0,cnt2=0; static JButton bt1,bt2; static Bt btLs; public static void main(String arg[]){ MyFrame mf = new MyFrame("One Listener",50,80,200,150); mf.setLayout(new FlowLayout()); bt1 = new JButton("butt1"); bt2 = new JButton("butt2"); mf.add(bt1); mf.add(bt2); btLs = new Bt(); bt1.addActionListener(btLs); bt2.addActionListener(btLs); mf.validate(); } static class Bt implements ActionListener{ public void actionPerformed(ActionEvent ev){ if (ev.getSource() == bt1){ System.out.println("butt1: "+ ++cnt1+" times clicked"); } if (ev.getSource() == bt2){ System.out.println("butt2: "+ ++cnt2+" times clicked"); } } } } |
getActionCommand()
(for the components with command string - Button, Check boxes, Menu Item ... )
static
class Bt implements ActionListener{ public void actionPerformed(ActionEvent ev){ if (ev.getActionCommand().equals("butt1")){ System.out.println("butt1: "+ ++cnt1+" times clicked"); } if (ev.getActionCommand().equals("butt2")){ System.out.println("butt2: "+ ++cnt2+" times clicked"); } } } |
Frame as Listener
import
java.awt.event.*; import javax.swing.* ; public class MyFrame extends JFrame implements ActionListener{ int cnt1,cnt2; MyFrame(String name,int x, int y, int ln, int ht){ this.setBounds(x, y, ln, ht); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle(name); cnt1=cnt2=0; } public void actionPerformed(ActionEvent ev){ if (ev.getActionCommand().equals("butt1")){ System.out.println("butt1: "+ ++cnt1+" times clicked"); } if (ev.getActionCommand().equals("butt2")){ System.out.println("butt2: "+ ++cnt2+" times clicked"); } } } import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class Test { static int cnt1=0,cnt2=0; public static void main(String arg[]){ MyFrame mf = new MyFrame("ButtonOne",50,80,200,150); mf.setLayout(new FlowLayout()); JButton bt1 = new JButton("butt1"); JButton bt2 = new JButton("butt2"); mf.add(bt1); mf.add(bt2); bt1.addActionListener(mf); bt2.addActionListener(mf); mf.validate(); } } |
Add and remove components
needs
import
java.awt.event.*; import javax.swing.* ; public class MyFrame extends JFrame{ MyFrame(String name,int x, int y, int ln, int ht){ this.setBounds(x, y, ln, ht); this.setVisible(true); this.setTitle(name); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } ---------------------------------------------------- import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Test { static JButton bt=null; static MyFrame mf=null,mfc=null; public static void main(String arg[]){ mfc = new MyFrame("ButtonControl",10,80,200,150); mfc.setLayout(new FlowLayout()); mf = new MyFrame("Buttons",10,250,200,150); mf.setLayout(new FlowLayout()); JButton btc1=new JButton("add a new button"); btc1.addActionListener(new AdBt()); mfc.add(btc1); JButton btc2 = new JButton("remove the button"); btc2.addActionListener(new RmBt()); mfc.add(btc2); mfc.validate(); } static class AdBt implements ActionListener{ public void actionPerformed(ActionEvent arg0) { if(bt == null){ bt = new JButton("added button"); mf.add(bt); mf.validate(); //or bt.revalidate(); } } } static class RmBt implements ActionListener{ public void actionPerformed(ActionEvent arg0) { if(bt != null){ mf.remove(bt); mf.setVisible(false); mf.setVisible(true); // or mf.repaint(); bt = null; } } } } |
setEnabled(true/false), Listeners with constructors
import
java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyFrame extends JFrame{ MyFrame(String name){ this.setBounds(200, 250, 250, 200); this.setVisible(true); this.setTitle(name); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } //---------------------------------------------------- import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Test { static JButton bt[]; public static void main(String arg[]){ MyFrame mf = new MyFrame("activate/desactivate"); bt = new JButton[4]; mf.setLayout(new FlowLayout()); Activ act = new Activ(); bt[0]= new JButton("activate all"); mf.add(bt[0]); bt[0].addActionListener(act); for(int i=1;i<bt.length;i++){ bt[i]= new JButton("desactivate "+ i); mf.add(bt[i]); bt[i].addActionListener(new Desactiv(i)); } mf.validate(); } static class Desactiv implements ActionListener{ int n; Desactiv(int n){ this.n = n; } //Constructor public void actionPerformed(ActionEvent ev) { bt[n].setEnabled (false) ; } } static class Activ implements ActionListener{ public void actionPerformed(ActionEvent ev) { for(int i = 1; i<bt.length; i++){ bt[i].setEnabled (true) ; } } } } |
JPanel
import
java.awt.event.*; import javax.swing.* ; public class MyFrame extends JFrame{ MyFrame(String name,int x, int y, int ln, int ht){ this.setBounds(x, y, ln, ht); this.setVisible(true); this.setTitle(name); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } ---------------------------------------------------- import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Test { static Button bt1,bt2,bt3,bt4; static JPanel jp1,jp2; public static void main(String arg[]){ MyFrame mfc=new MyFrame( "ButtonControl",10,80,200,150); mfc.setLayout(new FlowLayout()); jp1 = new JPanel(new FlowLayout()); jp2 = new JPanel(new FlowLayout()); jp1.setBackground(Color.yellow); jp2.setBackground(Color.green); mfc.add(jp1); mfc.add(jp2); bt1 = new Button("show green"); bt2 = new Button("hide green"); bt3 = new Button("show yellow"); bt4 = new Button("hide yellow"); jp1.add(bt1); jp1.add(bt2); jp2.add(bt3); jp2.add(bt4); bt1.addActionListener(new Show(2)); bt2.addActionListener(new Hide(2)); bt3.addActionListener(new Show(1)); bt4.addActionListener(new Hide(1)); mfc.validate(); } static class Hide implements ActionListener{ int npan; Hide(int i){this.npan = i;} // Constructor public void actionPerformed(ActionEvent ev) { if(npan == 1)jp1.setVisible(false); else jp2.setVisible(false); } } static class Show implements ActionListener{ int npan; Show(int i){ this.npan =i;} //Constructor public void actionPerformed(ActionEvent ev) { if(npan == 1)jp1.setVisible(true); else jp2.setVisible(true); } } } |
Check boxes
import java.awt.*; import javax.swing.* ; public class MyFrame extends JFrame{ MyFrame(String name){ this.setBounds(10, 10, 150, 120); this.setVisible(true); this.setLayout(new FlowLayout()); this.setTitle(name); this. setDefaultCloseOperation(EXIT_ON_CLOSE); } } ----------------------------------------------------------------------------- import java.awt.*; import java.awt.event.*; import javax.swing.* ; public class Test { static JCheckBox chck1,chck2; static Vrfy vr = new Vrfy(); public static void main(String arg[]){ MyFrame fm=new MyFrame("Chck"); chck1 = new JCheckBox ("Test",true) ; JButton bt1 = new JButton("vrfy"); chck2 = new JCheckBox ("Test 1") ; JButton bt2 = new JButton("cnvrt"); fm.add(chck1); fm.add(bt1); fm.add(chck2); fm.add(bt2); chck1.addActionListener(vr); //Action listener chck2.addItemListener(new Vrfy1()); //Item State changed listener bt1.addActionListener(vr); bt2.addActionListener(new Cnvrt()); fm.getContentPane().validate(); } static class Vrfy implements ActionListener{ public void actionPerformed(ActionEvent ev){ System.out.print("Ev_lsn_chck1:"+chck1.isSelected()); System.out.println("\tEv_lsn_chck2:"+chck2.isSelected()+"\n"); } } static class Vrfy1 implements ItemListener{ public void itemStateChanged (ItemEvent ev){ System.out.print("It_lsn_chck1:"+chck1.isSelected()); System.out.println("\tIt_lsn_chck2:"+chck2.isSelected()+"\n"); } } static class Cnvrt implements ActionListener{ public void actionPerformed(ActionEvent ev){ if (chck1.isSelected())chck1.setSelected(false); else chck1.setSelected(true); if (chck2.isSelected())chck2.setSelected(false); else chck2.setSelected(true); } } } |
Text Fields,
Text Areas
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyFrame extends JFrame implements ActionListener,FocusListener{ JTextField tf1,tf2,tf3; JTextArea ta; MyFrame(){ this.setSize(300,300); this.setLayout(new FlowLayout()); tf1 = new JTextField("initial", 10); tf2 = new JTextField(10); tf3 = new JTextField(10); ta = new JTextArea(15,10); tf2.setEditable(false); this.add(tf1); this.add(tf2); this.add(tf3); this.add(ta); tf3.addActionListener(new AdTa()); tf1.addActionListener(this) ; tf1.addFocusListener(this) ; this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent ev){ tf2.setText(tf1.getText()); } public void focusGained (FocusEvent e){ System.out.println("Get focus tf1"); } public void focusLost (FocusEvent e){ System.out.println("Lost focus tf1"); } class AdTa implements ActionListener{ public void actionPerformed(ActionEvent arg0) { ta.append(tf3.getText()+"\n"); tf3.setText(""); } } public static void main(String arg[]){ MyFrame mf = new MyFrame(); } } |
import java.awt.*; import java.awt.event.* ; import javax.swing.* ; class MyMenu extends JFrame { JMenuBar mb; JTextField t; public MyMenu () { setTitle ("Menu example") ; setSize (400, 440) ; t = new JTextField(3); setLayout(new FlowLayout()); add(t); ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent ev){ t.setText( ((JMenuItem)ev.getSource()).getText()); } }; mb = new JMenuBar() ; JMenu[] menus = { new JMenu("menu 1"), new JMenu("menu 2"), new JMenu("menu 3")}; for(int i = 0; i < menus.length; i++) mb.add(menus[i]); setJMenuBar(mb); JMenuItem[] items = { new JMenuItem("it1"), new JMenuItem("it2")}; for(int i = 0; i < items.length; i++){ items[i].addActionListener(al); menus[0].add(items[i]); } menus[0].addSeparator(); ButtonGroup group = new ButtonGroup() ; JRadioButtonMenuItem bt[] = { new JRadioButtonMenuItem("bt1"), new JRadioButtonMenuItem("bt2")}; bt[0].setToolTipText ("attention - radio button!") ; // tooltip for(int i = 0; i < bt.length; i++){ group.add(bt[i]); bt[i].addActionListener(al); menus[0].add(bt[i]); } menus[0].addSeparator(); JCheckBoxMenuItem cb[]= {new JCheckBoxMenuItem("chk1"), new JCheckBoxMenuItem("chk2"),new JCheckBoxMenuItem("chk3")}; for(int i = 0; i < cb.length; i++){ menus[0].add(cb[i]); cb[i].addActionListener(al); } this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setVisible(true); } public static void main(String arg[]){ MyMenu fm = new MyMenu(); } } |
import javax.swing.* ; import java.awt.*; class MyFrame extends JFrame{ MyFrame () { this.setTitle ("Example screen size") ; Toolkit tk = Toolkit.getDefaultToolkit() ; Dimension dimScr = tk.getScreenSize() ; this.setSize (dimScr.width/2, dimScr.height/2) ; this.setVisible(true); } } public class Test { public static void main(String arg[]){ MyFrame mf = new MyFrame(); Dimension dimFrame = mf.getSize(); System.out.println(dimFrame.width+":"+dimFrame.height); } } |
import java.awt.*; import javax.swing.*; public class Disposition extends JFrame{ MyPanel pan; public Disposition(){ setTitle ("Disposition") ; setSize (380, 220) ; pan = new MyPanel(); add(pan); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } class MyPanel extends JPanel{ public void paintComponent(Graphics g){ super.paintComponent(g) ; int x=10,y=10; String s[] = {"one ","two ","three "}; FontMetrics fm = g.getFontMetrics(); for(int i =0;i<s.length;i++){ g.drawString( s[i],x, y); x+=fm.stringWidth(s[i]); } x=10; for(int i =0;i<s.length;i++){ y+=fm.getHeight(); g.drawString( s[i],x, y); } } } public static void main(String arg[]){ Disposition d = new Disposition(); } } |
import javax.swing.* ; import java.awt.* ; class MyFont extends JFrame { JPanel pan; MyFont (){ setTitle ("Fonts") ; setSize (320, 150) ; pan = new MyPanel() ; add(pan) ; setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } class MyPanel extends JPanel { public void paintComponent(Graphics g){ super.paintComponent(g) ; FontMetrics fm = g.getFontMetrics() ; String fnts[] = GraphicsEnvironment.getLocalGraphicsEnvironment() .getAvailableFontFamilyNames() ; int x=10, y=20; g.drawString("by default: "+g.getFont().getFontName()+ g.getFont().getSize(),x,y); //default font y+=fm.getHeight()+10; Font fn = new Font ("Serif", Font.BOLD+Font.ITALIC, 20) ; g.setFont(fn); g.drawString (fn.getFontName()+" "+fn.getSize(), x, y) ; fn = new Font(fnts[3],Font.PLAIN, 25); y+=fm.getHeight()+10; g.setFont(fn); g.drawString (fn.getFontName()+" "+fn.getSize(), x, y) ; } } public static void main(String arg[]){ new MyFont(); } } |