December 31, 2009

Java Swing Example

« HTML convert to Pdf in Java | Main | Beanshell Example »
Java Swing is a graphical user interface API, which belongs to the Java Foundation Classes (JFC). The API is based on the composite design pattern. That's why Swing GUIs have a hierarchically oriented structure.


Furthermore Java Swing have the following features:
  • LayoutManagers (BorderLayout, GridBagLayout, ...), which allows a high flexibility in arrangement of GUI components
  • Pluggable Look&Feels
  • Drag&Drop functionality
  • and so on
  • Lighweight Dialog Components
    • JPanel
    • JButton
    • JTextArea
    • JMenuBar
    • ...
The following example, describes how to build a basic Java Swing application:
package de.developersblog.swingexample;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;

/**
 *
 * @author rafsob
 */
public class MainFrame extends JFrame {

    public MainFrame() {
        super("Swing Basic Example");
        //set layout manager
        this.setLayout(new BorderLayout());
        //set close action
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //add a menu bar with a file menu and open menu item
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        menuBar.add(fileMenu);
        JMenuItem openItem = new JMenuItem("Open");
        fileMenu.add(openItem);
        //set as stand menu bar of main frame
        this.setJMenuBar(menuBar);
        //create a text area in center
        JTextArea textArea = new JTextArea();
        textArea.setText("example text ...");
        //add to jframe component and set to the center
        this.add(textArea, BorderLayout.CENTER);

    }

    public static void main(String[] args) {
        MainFrame frame = new MainFrame();
        frame.setSize(800, 600);
        frame.setVisible(true);
    }
}
Regards
Rafael Sobek

Technorati Tags:

Posted by rafael.sobek at 12:30 AM in Java

 

[Trackback URL for this entry]

Comment: Anders at So, 6 Nov 10:13 AM

Thanks!

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
 
test