2014-01-26 4 views
-3

Я играю с 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); 
    } 
} 

Переменная, к которой я пытаюсь получить доступ, - это «счетчик».

+0

В чем проблема? –

+0

сообщение об ошибке от BlueJ: «счетчик переменных, возможно, не был инициализирован» на этой линии: счетчик JLabel = новый JLabel (счетчик «+ счетчик»); – user3236859

ответ

1

Несколько вещей, которые вы должны сделать:

  1. Переименуйте свои поля: у вас есть две переменные с именем counter.
  2. Во-вторых, вы хотите переместить свой JLabel выше метода actionPerformed и объявить его final, чтобы вы могли получить к нему доступ из actionPerformed.
  3. Я не вижу, где вы добавили JLabel к панели, так что я добавил, что линия

Это должно делать то, что вы хотите:

import java.awt.event.*; 
import javax.swing.*; 

public class JButtonTester { 

    static int counter = 0; 

    public static void main(String[] args) { 

     final JLabel counter_label = new JLabel(); 
     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"); 
       counter_label.setText("Count: " + counter); 
      } 
     } 
     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"); 
       counter_label.setText("Count: " + counter); 
      } 
     } 
     JFrame firstFrame = new JFrame(); 
     JPanel firstPanel = new JPanel(); 
     firstPanel.add(counter_label); 

     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); 
    } 
} 
1

Доступ к статической переменной из другого класса будет означать, чтобы имя переменной было переименовано в имя класса, поскольку static означает, что это переменная класса. Поэтому, так как счетчик является статическим переменным классом JButtonTester, чтобы получить доступ счетчика из другого класса вы бы сказали JButtonTester.counter

JLabel counter = new JLabel("Count: " + JButtonTester.counter); 
+0

Ничего себе, спасибо за быстрый и суперчувствительный ответ, Джош. Это сработало! Я не уверен, почему это было необходимо. Не является ли переменная в рамках основного метода? – user3236859

+1

Это решение работает, потому что у вас есть две переменные с именем 'counter'. Один из них - «int», другой - «JLabel». Если вы переименуете свой ярлык в 'counter_label', это тоже сработает. – ryvantage

+0

Спасибо за разъяснение @ryvantage –

1

Ты Грань неправильно

JLabel counter = new JLabel("Count: " + counter); 

счетчик ссылка к JLabel вы создаете, используйте другое имя переменной

Смежные вопросы