java - 单击按钮时将变量值返回给 main

标签 java swing jframe jbutton propertychangelistener

我希望每次单击按钮时 main 都应该打印 hello(在弹出的对话框中)。所以我设计了下面的程序,但它似乎不起作用。该程序编译并执行得很好,但是当我单击按钮时,我没有看到弹出任何对话框。我已经放置了 boolean 变量 (button_clicked) 的 getter 和 setter,其值正在 main() block 中进行测试。 知道的请帮忙..

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

class abc extends JFrame implements ActionListener{

boolean button_clicked = false;
JButton b1;

abc(){
    this.setSize (400, 400);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.createUI();
}

void createUI(){
    this.setLayout(null);
    b1 = new JButton("x");
    b1.setSize(110,30);
    b1.setLocation(10,210);
    this.add(b1);

    b1.addActionListener(this);
}

public boolean isButton_clicked() {
    return button_clicked;
}

public void setButton_clicked(boolean button_clicked) {
    this.button_clicked = button_clicked;
}


public void actionPerformed(ActionEvent arg0) {
    button_clicked = true;

    //I don't want to print the dialogue box from here..
    //I want to keep everything under main()'s control.
}

}


public class tempMain extends JFrame {

public static void main(String[] args) {
    abc temp = new abc();
    temp.setVisible(true);
    while(true){
        if(temp.isButton_clicked())
            JOptionPane.showMessageDialog(null, "Hello");
    }
}

}

最佳答案

JOptionPane.showMessageDialog() 调用移至 actionPerformed() 方法下,并删除 下的 while() 内容main 方法。

关于java - 单击按钮时将变量值返回给 main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12183212/

相关文章:

java - Spring MimeMessageHelper : AddressException when adding multiple CC

java - 如何检查文本字段是否为空?

Java JButton 在 If 语句中不创建

java - 如何在两个框架之间分割一个框架?

java - 如何用 Java 打开网页?

java - "Linking"Java 中的 JComponent?

java - 禁用 URLClassLoader 中的缓存

java - 使用 AspectJ 的 AOP 在 Spring 不起作用?

java - 如何在java中使用 vector 定义表模型

java - JFrame 重绘后不刷新