我正在玩JFrames的樂趣,並不能完全得到一個面板來顯示一個靜態變量。我會很感激任何幫助。這裏是我使用的代碼:使JLabel可以訪問靜態變量?
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);
}
}
我試圖訪問的變量是「計數器」。
問題是什麼? –
來自BlueJ的錯誤消息:「可變計數器可能未被初始化」 在這一行上:JLabel counter = new JLabel(「Count:」+ counter); – user3236859