import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class Incdec extends JPanel implements ActionListener { /** * Our internal components that we need to remember */ protected JButton upButton, downButton; protected JLabel label; /** * Our data, initialized inline here */ protected int value = 0; protected int min = 0; protected int max = 100; protected int incr = 1; public Incdec () { // Put a border on our JPanel // default color, user can modify later setBorder (new LineBorder(Color.RED, 1)); // Use vertical grid layout to hold our buttons and stuff setLayout (new GridLayout (3, 1)); // Our internal widgets: // Our up button upButton = new JButton ("+"); upButton.addActionListener (this); add (upButton); // Our label widget label = new JLabel (); label.setHorizontalAlignment (JLabel.CENTER); refreshLabel (); add (label); // Our down button downButton = new JButton ("-"); downButton.addActionListener (this); add (downButton); } /** * Common callback for both buttons, * we use ivar to disambiguate. */ public void actionPerformed (ActionEvent e) { if (e.getSource()==upButton) value += incr; else if (e.getSource()==downButton) value -= incr; // Clamp at bounds if (value > max) value = max; if (value < min) value = min; // Update our label widget to match refreshLabel (); } /** * Common code fragment, extracted to here */ protected void refreshLabel() { label.setText (String.valueOf (value)); } /** * Just as an example, we let user customize border color here */ public void setBorderColor (Color color) { setBorder (new LineBorder(color, 1)); } public int getValue() { return value; } }