JSlider เป็นคลาสย่อยของ JComponent คลาสและคล้ายกับแถบเลื่อนซึ่งอนุญาตให้ผู้ใช้เลือกค่าตัวเลขจากช่วงค่าจำนวนเต็มที่ระบุ มีปุ่มหมุนที่สามารถเลื่อนไปตามช่วงของค่าต่างๆ และสามารถใช้เพื่อเลือกค่าที่ต้องการได้ JSlider สามารถสร้าง ChangeListener ส่วนต่อประสานและวิธีการที่สำคัญของ JSlider คือ getMaximum(), getMinimum(), getOrientation() , getValue() และ setValue() . ตำแหน่งเริ่มต้น ของ JSlider เป็น แนวนอน และเรายังสามารถกำหนดตำแหน่งเป็นแนวตั้งโดยทางโปรแกรมโดยการเลือกรายการเมนูจากแถบเมนู มันสามารถสร้าง ActionListener อินเทอร์เฟซสำหรับรายการเมนูเหล่านี้และตั้งค่าการวางแนวโดยใช้ setOrientation () เมธอดของคลาส JSlider ใน actionPerformed() วิธีการ
ตัวอย่าง
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JSliderVerticalHorizontalTest extends JFrame implements ActionListener {
private JSlider slider;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem menuItem1, menuItem2;
public JSliderVerticalHorizontalTest() {
setTitle("JSliderVerticalHorizontal Test");
setLayout(new FlowLayout());
menuBar = new JMenuBar();
menu = new JMenu("JSlider Orientation");
menuItem1 = new JMenuItem("HORIZONTAL");
menuItem2 = new JMenuItem("VERTICAL");
menu.add(menuItem1);
menu.add(menuItem2);
menuItem1.addActionListener(this);
menuItem2.addActionListener(this);
menuBar.add(menu);
setJMenuBar(menuBar);
slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 15);
add(slider);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JSliderVerticalHorizontalTest();
}
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("HORIZONTAL"))
slider.setOrientation(JSlider.HORIZONTAL);
else if (ae.getActionCommand().equals("VERTICAL"))
slider.setOrientation(JSlider.VERTICAL);
}
} ผลลัพธ์

