Java Swing

Java Swing

Swing elements are subclasses from AWT package. Three classes are known:

  • top-levelcontainers such as JFrame, JDialog and JApplet. These are components which can have an own window and form the outer layer which can contain a menu (optional) and a contentpane.
  • Container classes that can contain other components such as JPanel or JScrollPane.
  • Components such as JLabel, JButton etc.

A gui contains minimally a Swing class extending the JFrame.

JFrame

Is standard for main window (JDialog for help windows). Contains standard a contentPane (container in which components can be placed) and has several settings which can be set as size and title.

// class definition
public class MijnFrame extends JFrame{
  private static final int FRAME_WIDTH = 600;
  private static final int FRAME_HEIGHT = 200;

// constructor
  public MijnFrame() {
    super();
    initialize();
  }
  
  // initial gui setup
  private void initialize() {
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    this.setTitle("Mijn Frame");
    this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    this.setLocation((dim.width - FRAME_WIDTH) / 2 , (dim.height - FRAME_HEIGHT)/ 2);

  }

// main function to start gui from command line
    public static void main(String[] args) {
    MijnFrame mf = new MijnFrame();
    mf.setVisible(true);
    mf.setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
}

Instead of setSize(), one can also use pack() to automatically adjust frame size to component features. In the context of dynamic gui content, the function revalidate() comes into play.

Within the content pane other JComponents such as JList and basis components such as JLabel can be placed.

pane.add(new JButton("Button name"));

All components are containers and have container methods such as setLayout() , setBounds(), and add(). It is also possible to manage all components that are contained in the container by these methods:

  • getComponentCount()
  • getComponent(int n)
  • getComponents()
  • remove (int index)
  • remove(Component comp)
  • removeAll()
  • getParent()

Layout manager

  • Null Layout: free to choose
  • Flow Layout: places components next to each other, at end pane new row. Changing the size of the pane means that components placement will be adjusted. Size of individual components (preferred size) can be customized. This layout is default for e.g. JPanel
  • Grid Layout: Matrix with chosen rows and columns determine layout. Size of component changes with number of components. Size of individual components can not be customized.
  • Border Layout: Pane is divided in 5 areas, in each can a component be placed. Size of individual components is not customizable. This is default layout for contentPane
Container pane = getContentPane();
LayoutManager mgr = new FlowLayout(FlowLayout.LEADING, 4, 4);
pane.setLayout(mgr);
JButton button = new JButton("My text");
button.setPreferredSize(new Dimension(30,20));
pane.add(button);

Color and Lettertype

Color and Font are classes that can be instantiated with attributes specifying the type of color / Lettertype etc and can be set like this

JTextField textfield = new JTextField();
Font f = new Font("Monospaced",Font.BOLD, 18);
textfield.setFont(f);
textfield.setBackground(Color.DARK_GRAY);
textfield.setForeground(Color.WHITE);
    

Buttons and Lists

JButton is the most simple swing button component. JToggleButton has states, JCheckBox/JRadioButton are more or less same: Buttons that can be selected. They can be arranged in groups by adding them to an instance of ButtonGroup: which allows to select only 1 out of the whole group.

A group of choice options can also be created by instances of the JList (several choices) or JComboBox (one choice at a time) class.

These classes separate appearance (gui element) from (data)model by utilizing a model class. You can specify the model manually or use a default one.

DefaultListModel model = new DefaultListModel();
JList lijst = new JList(model);
for (int i = 0; i < 10; i++) {
  model.addElement( i + "");
}

JFileChooser

File chooser is a pop up window with a dialog box which can be used to select a file for data import/export.


kiezer = new JFileChooser();
BufferedReader lezer;
int gekozen = kiezer.showDialog(this, "open/Create");
if (gekozen == JFileChooser.APPROVE_OPTION){
File bestand = kiezer.getSelectedFile();
      try {
        lezer = new BufferedReader(new FileReader(bestand));
      }
      catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }