我编写了一些简单的代码,以便每次单击按钮时将进度条增加1。这是我的代码。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JProgressBar;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class BtnProgTest extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BtnProgTest frame = new BtnProgTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public BtnProgTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setBounds(115, 114, 183, 14);
contentPane.add(progressBar);
int count = 0;
progressBar.setMaximum(100);
JButton btnProgress = new JButton("Progress");
btnProgress.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(count<100) {
count++; //error here
progressBar.setValue(count);
}
}
});
btnProgress.setBounds(160, 166, 89, 23);
contentPane.add(btnProgress);
}
}
我收到的错误消息是“在封闭范围内定义的局部变量计数必须是最终的或有效的最终”。我无法真正看到范围错误,如果有人可以编辑我的代码以便错误不存在,我会非常感激。
答案 0 :(得分:1)
在类级别移动count
变量,它应该可以正常工作。
另外,作为改进,我建议使用lambda表达式将动作侦听器添加到按钮(它更干净):
btnProgress.addActionListener(e -> {
if (count < 100) {
count++;
}
});
答案 1 :(得分:1)
如上所述,对于在ActionListener
之外声明的任何变量,必须将其声明为final
。试试这个工作:
public class BtnProgTest extends JFrame {
// declare these as class's member variables
private JProgressBar progressBar;
private int count = 0;
public BtnProgTest() {
......
// progressBar is now a class's member variable
this.progressBar = new JProgressBar();
.....
JButton btnProgress = new JButton("Progress");
btnProgress.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
BtnProgTest.this.updateProgressBar();
}
});
......
}
private void updateProgressBar() {
if (this.count < 100) {
this.count++;
this.progressBar.setValue(this.count);
}
}
....
}
答案 2 :(得分:0)
我猜你的actionPerformed中的计数是未知的,因为你在“new ActionListener()”范围内