3

具有“ChangeListener”接口和句柄“ChangeEvent”的 JSlider,当滑块值更改时将更改 JLabel 背景颜色。请帮助我,我做不到。在此先感谢。我无法应用 JLabel

              package org.kodejava.example.swing;
              import javax.swing.*;
               import javax.swing.event.ChangeEvent;
               import javax.swing.event.ChangeListener;
              import java.awt.*;
           public class JSliderDemo extends JPanel implements ChangeListener {
private JTextField field;

public JSliderDemo() {
    initializeUI();
}

private void initializeUI() {
    setLayout(new BorderLayout());
    setPreferredSize(new Dimension(400, 100));

    //
    // Creates an instance of JSlider with a horizontal
    // orientation. Define 0 as the minimal value and
    // 50 as the maximum value. The initial value is set
    // to 10.
    //
    JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 10);

    slider.setPaintTicks(true);
    slider.setPaintLabels(true);
    slider.setMinorTickSpacing(1);
    slider.setMajorTickSpacing(10);

    slider.addChangeListener(this);

    JLabel label = new JLabel("The Value:");
    field = new JTextField(5);

    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    panel.add(label);
    panel.add(field);

    add(slider, BorderLayout.NORTH);
    add(panel, BorderLayout.SOUTH);
}

public void stateChanged(ChangeEvent e) {
    JSlider slider = (JSlider) e.getSource();

    //
    // Get the selection value of JSlider
    //
    field.setText(String.valueOf(slider.getValue()));
}

public static void showFrame() {
    JPanel panel = new JSliderDemo();
    panel.setOpaque(true);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("Slider Example");
    frame.setContentPane(panel);
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JSliderDemo.showFrame();
        }
    });
}
}
4

2 回答 2

6
  1. JLabel是透明的,然后必须改变它的不透明度JLabel.setOpaque(true)

  2. 阅读 Oracle 教程如何使用滑块

于 2012-12-29T20:14:54.930 回答
0

JLabel 是透明的,不能直接改变它的背景颜色。

您可以从 JLabel 扩展并覆盖paint方法

或更改面板的背景颜色。您将 JLabel 放在面板上,当滑块移动时,只需更改该面板的 bgcolor。由于 JLabel 是透明的,您将看到更改。

至于代码尝试在你的 statechange 方法中添加这样的东西

panel.setBackground(new Color(int,int,int));//ints could be slider.getValue();
于 2013-01-01T06:33:11.707 回答