Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีเปลี่ยนตำแหน่ง JSlider เป็น Horizontal/Vertical โดยโปรแกรมใน Java

JSlider เป็น subclass ของ JComponent คล้าย scroll bar ให้ user เลือกค่าตัวเลขจากช่วง integer values ที่กำหนด มี knob เลื่อนบนช่วงค่า ใช้เลือกค่าเฉพาะ JSlider สร้าง ChangeListener interface เมธอดสำคัญ ได้แก่ getMaximum(), getMinimum(), getOrientation(), getValue() และ setValue() Default position ของ JSlider คือ horizontal สามารถตั้งค่าเป็น vertical โดยเลือก menu item จาก menu bar สร้าง ActionListener สำหรับ menu items และตั้งค่า orientation ด้วย 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);
    }
}

Output

วิธีเปลี่ยนตำแหน่ง JSlider เป็น Horizontal/Vertical โดยโปรแกรมใน Java

วิธีเปลี่ยนตำแหน่ง JSlider เป็น Horizontal/Vertical โดยโปรแกรมใน Java