Java - 是否可以将setEditable(boolean b)应用于JSlider /

时间:2014-01-28 22:51:27

标签: java swing jslider

在我的程序中我需要在某些情况下禁用我的JSlider,但不知道如何。我尝试了setFocusable(false),但是没有用......提前谢谢!

2 个答案:

答案 0 :(得分:6)

通过使用JSlider属性,您可以更改/限制用户与enabled的互动。

SliderState

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class SliderTest {

    public static void main(String[] args) {
        new SliderTest();
    }

    public SliderTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final JSlider slider = new JSlider();
                final JCheckBox checkBox = new JCheckBox();
                checkBox.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        slider.setEnabled(checkBox.isSelected());
                    }
                });
                checkBox.setSelected(true);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridwidth = GridBagConstraints.REMAINDER;
                frame.add(slider, gbc);
                frame.add(checkBox, gbc);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

答案 1 :(得分:5)

尝试使用setEnabled(boolean)方法。默认情况下,所有JComponents都会继承它。