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