【问题标题】:Java Swing object recognition by functionJava Swing对象识别功能
【发布时间】:2017-02-22 17:10:57
【问题描述】:

我该怎么做才能通过do_something 函数识别button 2?我想在点击后更改button2 文本,但收到错误消息:button2 cannot be resolved

class myClass {
    public static int counter = 0;
    public static void do_something() {
    button2.setText(Integer.toString(counter));
  }

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setLayout(new GridLayout(3, 2));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton button = new JButton("button 1");
    frame.add(button);
    JButton button2 = new JButton("button 2");
    button2.addActionListener(e -> do_something());
    frame.add(button2);
    frame.pack();
    frame.setVisible(true);     
  }
}

【问题讨论】:

标签: java swing scope


【解决方案1】:

您需要在类外声明buttonbutton2(一些全局方法,并在您按下button2 时递增counter 变量):

package javaapplication1;

import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;

class myClass extends JFrame{

    static JButton button = new JButton("button 1");
    static JButton button2 = new JButton("button 2");
    public static int counter = 0;

    public static void do_something() {
        counter++;
        button2.setText(Integer.toString(counter));
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setLayout(new GridLayout(3, 2));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(button);

        button2.addActionListener(e -> do_something());
        frame.add(button2);
        frame.pack();
        frame.setVisible(true);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    相关资源
    最近更新 更多