A Simple Swing Program

  

If you have never written a Swing Program before, here’s a simple Swing Program to get you started
This program will show a frame, with a big “Click me!” button on in it as below


And here’s how it will look if you click the button
How our application will look , when clicked!

Ok, So here’s the code, It’s pretty self-explanatory, only the important-to-mention things are listed after the program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package net.javaswing.startingSwing;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
 
import javax.swing.*;
public class SimpleSwingFrame  {
public void createAndShowFrame(){
 
//Create a JFrame Object
//Pass the title as an argument to the constructor
//We make it final, so that we cann access it in the
//ActionListener inner class below
final JFrame frame = new JFrame(" A Simple Swing Example");
 
//Set the Size of the frame
frame.setSize(300, 300);
 
//Specify that, when the user closes this frame,
//the program should exit
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
//Add a JButton object. Pass the string that
//appears in the JButton as an argument
JButton button  =  new JButton("Click me!");
 
//Specify what will happen if you click the button
//by adding an ActionListener
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(frame, "Hi, Iam Swing!");
}
 
});
 
//Add this button to the Content Pane of the frame
frame.getContentPane().add(button);
 
//Make the frame visible
frame.setVisible(true);
}
 
public static void main(String[] args){
//Create an instance of our class
final SimpleSwingFrame example = new SimpleSwingFrame();
 
//Call the createAndShowFrame method in the
//EventDispatch thread
SwingUtilities.invokeLater(new Runnable(){
public void run(){
example.createAndShowFrame();
}
});
}
}

Two things to note here
1) See how you specify what to do when the button is pressed. You create an ActionListener class, write the code that you want in it’s actionPerformed method and pass it to the addActionListener() method

2) Note that createAndShowFrame() method is called in the invokeLater method. The invokeLater method makes sure that the creation of the frame, happens in the event dispatch thread and not the main thread in which the application is running








Leave a Reply





Popular Articles

Blog Categories

Monthly Archives

Resources