Я играю с 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 = новый JLabel (счетчик «+ счетчик»); – user3236859