As you know, I've been working with Java for the past two years. Java was the first programming language that I've learned even though C++ was more popular five years ago. I eventually learned C++ and thought I had forgotten Java. But it has incorporated into my everyday life.
It was Core Java that I first learned. I don't remember if they taught me Swing. But I remembered learning about Applets. I know the powerfulness of Swing but never really had a chance to learn about it. Now that I have some spare time to expand my knowledge and intelligence, I want to learn about this Java Swing.
So, as usual, I go to Java Sun website. One thing I like about Sun is that they have pretty good tutorials. But then to make a fair statement, I have never really tried other open source programming languages.
In order to make a Java Swing program, we need javax.swing.* package. GUI programs mostly about looks. So, in order to make a swing program more user friendly and better display, we need a few components from java.awt.* packages as well.
As with any first program about a new programming language, I started off with HelloWorld java. Here's my program :
public class HelloWorldSwing {
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI(){
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hellow World");
JPanel contentPane = new JPanel();
contentPane.setBackground(Color.red);
contentPane.setSize(100, 500);
contentPane.add(label,BorderLayout.CENTER);
frame.add(contentPane);
frame.pack();
frame.setVisible(true);
}
}
As you can see we need three components : JFrame, JPanel & JLabel. JFrame is the starting point of any Java Swing program. Creating a JFrame component is creating a window. It's the main container with other buttons such as close and minimize buttons. Then we create more components and add those to JFrame. In this program, we create a JLabel components for labels.
In order to add JLabel to JFrame, we need to call content pane. Content Pane exists inside JPanel. But in order to customize the content pane, we need to create a JPanel. As you saw in the code, I customized my content pane to have red background color through JPanel. I added label to content pane, which is added to JFrame.