【发布时间】:2014-01-26 05:27:25
【问题描述】:
我在玩 JFrames 是为了好玩,但不能让面板显示静态变量。我会很感激任何帮助。这是我正在使用的代码:
import java.awt.event.*;
import javax.swing.*;
public class JButtonTester
{
static int counter = 0;
public static void main(String[]args)
{
class ClickCounter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
counter++;
System.out.println("Congratulations, you clicked a button " + counter + " time(s)! This might just be your greatest accomplishment");
}
}
class ClickDecrement implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
counter--;
System.out.println("Congratulations, you clicked a button " + counter + " time(s)! This might just be your greatest accomplishment");
}
}
JFrame firstFrame = new JFrame();
JLabel counter = new JLabel("Count: " + counter);
JPanel firstPanel = new JPanel();
JButton firstButton = new JButton("Click me to increase your count!");
firstPanel.add(firstButton);
ActionListener firstListener = new ClickCounter();
firstButton.addActionListener(firstListener);
JButton secondButton = new JButton("Click me to decrease your count!");
firstPanel.add(secondButton);
ActionListener secondListener = new ClickDecrement();
secondButton.addActionListener(secondListener);
firstFrame.add(firstPanel);
firstFrame.setSize(200, 120);
firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstFrame.setVisible(true);
}
}
我试图访问的变量是“counter”。
【问题讨论】:
-
来自 BlueJ 的错误消息:“变量计数器可能尚未初始化”在这一行:JLabel counter = new JLabel("Count: " + counter);