import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; public class Incdec extends JPanel implements ActionListener, Adjustable { /** * 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 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 internal buttons, * we use ivar to disambiguate. * Then we fire the result to *our* listeners. */ public void actionPerformed (ActionEvent e) { int type = 0; if (e.getSource()==upButton) { value += incr; type = AdjustmentEvent.UNIT_INCREMENT; } else if (e.getSource()==downButton) { value -= incr; type = AdjustmentEvent.UNIT_DECREMENT; } // Clamp at bounds if (value > max) value = max; if (value < min) value = min; // Update our label widget to match refreshLabel (); // Make a new event with our new data AdjustmentEvent event = new AdjustmentEvent (this, AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED, type, value); // Send it to each of *our* listeners for (AdjustmentListener l: listenerList.getListeners (AdjustmentListener.class)) { l.adjustmentValueChanged (event); } } /** * Common code fragment, extracted to here */ protected void refreshLabel() { label.setText (String.valueOf (value)); } /** * Methods required by Adjustable, * listenerList is an ivar of JComponent, we access it here */ public void addAdjustmentListener(AdjustmentListener l) { listenerList.add (AdjustmentListener.class, l); } public void removeAdjustmentListener(AdjustmentListener l) { listenerList.remove (AdjustmentListener.class, l); } /** * Methods required by Adjustable, * though block vs. unit and visibleAmount don't really make sense for us */ public int getValue() { return value; } public int getMaximum() { return max; } public int getMinimum() { return min; } public int getOrientation() { return VERTICAL; } public int getUnitIncrement() { return incr; } public int getBlockIncrement () { return incr; } public int getVisibleAmount() { return 0; } public void setBlockIncrement(int b) { incr = b; } public void setMaximum(int max) { this.max = max; } public void setMinimum(int min) { this.min = min; } public void setUnitIncrement(int u) { incr = u; } public void setVisibleAmount(int v) { } public void setValue(int v) { value = v; refreshLabel (); } }