我是非常新的摇摆,但我尝试制作这个程序,创建一个滑块和一个标签。移动滑块(形式1到16)时,标签会发生变化。但是,我的标签没有更新,而是在滑动滑块时出现线程异常和其他错误。这是完整的代码:
package edu.cuny.brooklyn.cisc3120;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.*;
public class Gui extends JFrame {
private static final int limit = 4;
private static final int minInteger = 1;
private static final int maxInteger = 16;
private static JLabel currentGuess;
private static JSlider slider;
public Gui()
{
setLayout(new FlowLayout());
JSlider slider = new JSlider(JSlider.HORIZONTAL, minInteger, maxInteger, 1);
add(slider);
slider.setMajorTickSpacing(1);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
currentGuess = new JLabel("Current Guess: 1");
add(currentGuess);
SliderEvent e = new SliderEvent();
slider.addChangeListener(e);
}
public static class SliderEvent implements ChangeListener
{
public void stateChanged(ChangeEvent e)
{
currentGuess.setText("Current Guess: " + slider.getValue() );
}
}
public static void main(String[] args)
{
Gui guessingGame = new Gui();
guessingGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guessingGame.setTitle("Guessing Game");
guessingGame.setLocation(100, 100);
guessingGame.pack();
guessingGame.setVisible(true);
}
}
我重申我非常擅长挥杆。因此,如果我犯了一些愚蠢的错误,那就请放轻松。
答案 0 :(得分:1)
private static JSlider slider;
public Gui()
{
setLayout(new FlowLayout());
JSlider slider = new JSlider(JSlider.HORIZONTAL, minInteger, maxInteger, 1);
您正在定义滑块两次,一次作为实例变量(为null),另一次作为局部变量。
摆脱局部变量:
//JSlider slider = new JSlider(JSlider.HORIZONTAL, minInteger, maxInteger, 1);
slider = new JSlider(JSlider.HORIZONTAL, minInteger, maxInteger, 1);
此外,您不应该使用所有这些静态变量。这表明设计不佳。我建议您查看How to Use Sliders上Swing教程中的部分,了解可以显示更好的程序结构的演示代码。下载演示代码并根据您的要求进行修改。