我正在尝试让JSlider实时更新JLabel,但它只会出现错误。到目前为止,这是我的代码:
slider.addChangeListener(new ChangeListener() {
public void stateChanged() {
label.setText(String.valueOf(slider.getValue()));
}
});
谁能看到我出错的地方? 谢谢,
答案 0 :(得分:1)
我错了,您的代码中存在一个非常基本的错误:您的stateChanged方法错误,因为它需要ChangeEvent参数。改变
public void stateChanged() {
到
public void stateChanged(ChangeEvent e) {
编译器错误消息应告诉您所有这些,并且将来,您将要批判性地阅读这些消息,因为如果您这样做,它们将为您节省很多麻烦。
例如:
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderFoo extends JPanel {
private JSlider slider = new JSlider(0, 100, 50);
private JLabel label = new JLabel(" ", SwingConstants.CENTER);
public SliderFoo() {
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
label.setText(String.valueOf(slider.getValue()));
}
});
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Slider Value:"));
topPanel.add(label);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(5, 5));
add(topPanel, BorderLayout.PAGE_START);
add(slider);
}
private static void createAndShowGui() {
SliderFoo mainPanel = new SliderFoo();
JFrame frame = new JFrame("SliderFoo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}