Programmierpraktikum




Claudius Gros, SS2012

Institut für theoretische Physik
Goethe-University Frankfurt a.M.

Swing
Graphical User Interface (GUI)

Graphical User Interface (GUI)


Swing example

import javax.swing.*;                         // 'x' for extension
import java.util.*;                           // for sleeping

public class SimpleFrame { 
public static void main(String args[]) throws InterruptedException   
                                              // needed for sleeping
  {
  JFrame jf = new JFrame();                   // instantiation of a JFrame
  JLabel jlb = new JLabel("Hello World");     // instantiation of a JLabel
  jf.getContentPane().add(jlb);               // add label to content of frame
  jf.setSize(300, 200);                       // set frame size
  jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//  what to to when clicken away the window: remove it, free resources
  jf.setVisible(true);                        // show frame 
  System.out.println("JFrame panel lauched");
//
  Thread.sleep(3000);                         // wait 3 seconds
  jf.setLocationRelativeTo(null);             // move to center of screen
  System.out.println("JFrame panel relocated");
//
  Thread.sleep(3000);                        
  jlb.setFont(jlb.getFont().deriveFont(20f)); // set font size
  System.out.println("JLabel font resized");
//
  }
}    // end of class SimpleFrame

layers (panes)




frame and window hierarchy

moving colored JFrame

import javax.swing.*;                          // for the frame
import java.awt.*;                             // for colors
import java.util.*;                            // for sleeping

public class MovingScreen extends JFrame {

/* Constructor of MovingScreen.
 * Using 'this' is not necessary but increases readability.
 * 'title', 'size', .. are member variables of JFrame.
 **/
public MovingScreen() {
  this.setTitle("moving colors");
  this.setSize(300, 200);
  this.setDefaultCloseOperation(EXIT_ON_CLOSE); // exit program on close
  }

public static void main(String[] args) throws InterruptedException {
  MovingScreen ex = new MovingScreen();         // instantiation
  ex.setLocationRelativeTo(null);               // relative to screen center
  ex.setVisible(true);     
  int screenCenter_x = ex.getLocation(null).x;  // Point.x
  int screenCenter_y = ex.getLocation(null).y;  // Point.y
  for (int i=0;i<255;i++)
    {
    Thread.sleep(40);
    ex.getContentPane().setBackground(new Color(0,i,255-i));
    ex.setLocation(screenCenter_x+i,screenCenter_y+i);
    }
  } // end of MovingScreen.main()
}   // end of class MovingScreen

adding content to a frame




adding content using a container


adding content directly to the ContentPane

Swing components

import java.awt.*;                                   // for the container
import javax.swing.*;                                // for the frame

public class AddContentPane {

public static void main(String[] args) {
  JFrame frame = new JFrame("Various Components");
  frame.setSize(600, 150);
  frame.setLocationRelativeTo(null);
  frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

  Container content = frame.getContentPane();        // add to contentPane
  content.setLayout(new FlowLayout());               // one is necessary

  content.add(new JButton("JButton"));
  content.add(new JToggleButton("JToggleButton"));
  content.add(new JCheckBox("JCheckBox"));
  content.add(new Label("Label"));
  content.add(new JRadioButton("JRadioButton"));

  Font font = new Font("Arial Black",Font.PLAIN,20); // select a new font
  Component[] allComp = content.getComponents();     // get all components

  for (Component comp : allComp)                     // iteration
    {
    comp.setBackground(new Color(153,204,153));      // of component
    comp.setForeground(new Color(204,51,51));        // change font color
    comp.setFont(font);                              // change font sizes
    }
  content.setBackground(new Color(204,204,204));     // of contentPane

  frame.setVisible(true);                          // show
  }
}

events - making things happen



Java listener


public class MyClass implements ActionListener {
//   ActionListener is an Interfaces not a class and hence
//   implemented and not extended
 public void actionPerformed (){
//   mandatory: do stuff when action has been triggered
 }
}

simple Swing events

import java.awt.event.*;                // for events
import java.awt.*;                      // for colors
import javax.swing.*;                   // for JFrame
 
public class SimpleEvent
       extends JFrame                   // extending an class
       implements ActionListener        // implementing an interface
{
JButton button1, button2, button3;      // needed several times
JLabel label; 

/* Constructor.
 **/
 
public SimpleEvent(){
  this.setTitle("click buttons");       // title
  this.setSize(400, 200);               // size
  this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  this.setLocationRelativeTo(null);     // position

  this.label = new JLabel();            // initially empty

  this.button1 = new JButton("text");  
  this.button2 = new JButton("color");
  this.button3 = new JButton("exit");
 
  this.button1.addActionListener(this); // register listeners
  this.button2.addActionListener(this); // 'this' implements
  this.button3.addActionListener(this); // an ActionListener
 
  JPanel panel = new JPanel();          // for the content
  panel.add(button1);
  panel.add(button2);
  panel.add(button3);
  panel.add(label);
  panel.validate();
  this.add(panel);
}    // end of constructor

/* Main.
 **/
 
public static void main(String[] args) {
  SimpleEvent window = new SimpleEvent();
  window.setVisible(true);
}     
 
/* ActionPerformed is mandatory since SimpleEvent
 * implements ActionListener.
 **/
 
public void actionPerformed (ActionEvent ae){
  if(ae.getSource() == this.button1){
    label.setText("you successfully clicked button 1");
    }

  if(ae.getSource() == this.button2){
    label.setText(("changing colors of button 2"));
    button2.setBackground(new Color(230,230,130));
    }

  if (ae.getSource() == this.button3){
    System.exit(0);
    }
  }  // end of SimpleEvent.actionPerformed()
}    // end of SimpleEvent

list of events

event typ event processor event trigger
Action JButton button activation
Adjustment JScrollBar on change
CaretEvent JTextComponent moving cursor
Component Component changing visbility, size
Container Container changing content
Focus JComponent new focus (for typing)
Key JComponent keyboard activation
Menu JMenu on selection
Mouse JComponent mouse in/out
MouseMotion JComponent mouse motion

graphics and drawing

import javax.swing.*;           // for JFrame, JCompoent
import java.awt.*;              // for graphics objects

public class DrawingColor {
  public static void main(String[] args) {
  JFrame frame = new JFrame("drawing colors");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setSize(500,300);
  frame.setLocationRelativeTo(null);
  frame.getContentPane().add(new MyComponent());  // add content
  frame.setVisible(true);  
  }
}   // end of class DrawingColor

/** User defined component, extending the
  * abstract class JComponent.
  */
class MyComponent extends JComponent{
/** Paints the component when first shown or needed.
  * Overrides the super.paintComponent of the 
  * JComponent. Painting and drawing is down on a
  * Graphics object. Graphics2D extends Graphics and
  * has more options.
  */
  public void paintComponent(Graphics g){
  int width  = 200;
  int height = 120;
//
  g.setColor(Color.blue);                 // select color
  g.fillOval(20,20,width,height);         // filled elipse
  g.setColor(Color.cyan);
  g.fillOval(24,24,width,height); 
//
  g.setColor(Color.gray);
  g.fillRect(270+width/2,20+height/2,width/2,height/2);  // filled rectangle
//
  Graphics2D g2d = (Graphics2D)g;         // cast Graphics to Graphics2D
  g2d.setStroke(new BasicStroke(5));      // only availabe in Graphics2D
  g2d.setColor(Color.red);
  g2d.drawRect(270,20,width/2,height/2);   // borders thickness is stroke
//
  int[] xPoints = new int[200];
  int[] yPoints = new int[200];
  for (int x=0; x<200;x++)
    {
    xPoints[x] = 50 + 2*x;
    yPoints[x] = 200 + (int)(40.0*Math.sin(Math.PI*x/25.0));
    }
  g.setColor(Color.black);
  g.drawPolyline(xPoints,yPoints,xPoints.length);
  } // end of MyComponent.paintComponent()
}   // end of class MyComponent

exercise: GUI for Kepler problem

Write a GUI for the numerical solution of the Kepler problem with Runge-Kutta integration.