October 17th, 2022

OOP for GUI

  • You can enable and disable widgets using button.setEnabled(true | false)
  • Combo Box:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class ComboBox extends JComboBox<String> implements ItemListener {
	public ComboBox () {
		addItem ("one");
		addItem ("two");
		addItem ("three");
		addItem ("four");
		setSelectedItem ("three");
		addItemListener (this);
	}

	public void itemStateChanged (ItemEvent e) {
		if (e.getStateChange() == ItemEvent.SELECTED) {
	    System.out.println ("Combo: " + e.getItem());
		}
	}
}
  • Radio buttons:
    • Create your own widget (as a JPanel) that contains buttons.
    • ButtonGroup makes sure that only one button is selected at a time.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;

public class Radio extends JPanel implements ItemListener {
	public Radio () {
		// Border around our JPanel
		setBorder (new LineBorder(Color.BLUE, 1));

		ButtonGroup g = new ButtonGroup ();

		JRadioButton rb = new JRadioButton ("I", false);
		add (rb);
		g.add (rb);
		rb.addItemListener (this);

		rb = new JRadioButton ("II", true);
		add (rb);
		g.add (rb);
		rb.addItemListener (this);

		rb = new JRadioButton ("III", false);
		add (rb);
		g.add (rb);
		rb.addItemListener (this);

		rb = new JRadioButton ("IV", false);
		add (rb);
		g.add (rb);
		rb.addItemListener (this);
	}

	public void itemStateChanged (ItemEvent e) {
			// Reports every select or deselect, we filter out
			if (e.getStateChange()==ItemEvent.SELECTED) {
			    System.out.println ("Radio: " + ((JRadioButton)e.getItem()).getText());
			}
	}
}

Animations

  • Every x milliseconds, increment a frame variable and then re-draw the panel taking that frame variable into account.