Introduction to Java Swing

Guest Posts Steven





Swing is the primary Java GUI library. It provides graphical user interface(GUI) for Java programs, it’s easy to use and more components than the earlier AWT.

This article is intended to give a brief introduction to how to start using Swing, with an implication really simple just for you to learn how to write the code to create a window.

The main window for a GUI application is what we call a JFrame. This is the window in which all of the components are going to be added. Normally the components are first added to a JPanel and then that JPanel is added to the JFrame.

First Steps:

Here we create the main frame:

public class exampleJFrame extends JFrame {

  private JPanel _panel;

  /**
  * Create the frame.
  */
   public exampleJFrame() {
      setVisible(true); //we make the window visible
      setResizable(false); // if write false, you won’t be able to resize the window
      setTitle(“Example”); //you set the title for the window
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null); // you make the window appear at the center of the screen
      setSize(500,500); // you set the size of the window
      _panel = new JPanel();
      add(_panel); // we add the panel to the JFrame
   }

   public static void main(String[] args) {
      exampleJFrame example=new exampleJFrame();
   }

}


 

This will be the result:

Image

 

That was a very simple example of how to create a JFrame just to give an idea of what is Swing and how to use it.