SliderFrame (JSlider, JLabel, JTextfield, JButton)
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
// SliderFrame shows ChangeListener, KeyListener, ActionListener
public class SliderFrame extends JFrame implements ChangeListener, KeyListener, ActionListener {
JPanel panel = new JPanel(new BorderLayout());
JPanel panel1 = new JPanel(new FlowLayout());
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 20);
JLabel label = new JLabel("Value : ", JLabel.CENTER);
JTextField textfield = new JTextField(10);
JButton button = new JButton("Close");
public SliderFrame(String name) {
super(name);
this.add(panel);
this.panel1.add(label);
this.panel1.add(textfield);
this.panel.add(slider, BorderLayout.CENTER);
this.panel.add(panel1, BorderLayout.NORTH);
this.panel.add(button, BorderLayout.SOUTH);
this.slider.addChangeListener(this); // ChangeListener stateChanged
this.textfield.addKeyListener(this); // KeyListener keyTyped, keyPressed, keyReleased
this.button.addActionListener(this); // ActionListener actionPerformed
this.setSize(250, 150);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new SliderFrame("SliderFrame");
}
@Override
public void stateChanged(ChangeEvent e) {
JSlider s = (JSlider)e.getSource();
textfield.setText("" + s.getValue());
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
Toolkit.getDefaultToolkit().beep();
System.out.println("ENTER pressed");
JTextField t = (JTextField) e.getSource();
int value = Integer.parseUnsignedInt(t.getText());
slider.setValue(value);
}
}
@Override
public void actionPerformed(ActionEvent e) {
JButton b = (JButton)e.getSource();
if (b == button) {
this.setVisible(false);
this.dispose();
}
}
}