简体   繁体   English

Java - 这个简单的程序有什么问题?

[英]Java - What's wrong with this simple program?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Test extends JFrame{

    JLabel label = new JLabel("Leann will come again");
    JButton yesButton = new JButton("Yes");
    JButton noButton = new JButton("Yes");
    JPanel panel = new JPanel();

    public Test(){

        panel.add(label);
        panel.add(yesButton);
        panel.add(noButton);
        add(panel);
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addAction();

    }

    public void addAction(){
        yesButton.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JOptionPane.showMessageDialog(null, "Are you sure?");               
            }

        });

        noButton.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JOptionPane.showMessageDialog(null, "Too bad!");                
            }

        });
    }

    public static void main(String args[]){
        Test app = new Test();

    }

}

when I run this in my ubuntu computer with eclipse, it get's stop(terminate) without any errors. 当我在我的ubuntu计算机上使用eclipse运行它时,它会停止(终止)而没有任何错误。 There is no errors in the console either. 控制台中也没有错误。 And no syntax errors. 并且没有语法错误。

What's wrong? 怎么了? Is it because I run openjdk? 是因为我运行openjdk?

You don't set your frame to visible setVisible(true) 您没有将框架设置为可见的setVisible(true)

You should check out this tutorial: http://download.oracle.com/javase/tutorial/uiswing/components/frame.html 您应该查看本教程: http//download.oracle.com/javase/tutorial/uiswing/components/frame.html

You're creating an instance of Test, but that's all. 你正在创建一个Test实例,但就是这样。 You're never actually trying to show it. 你从来没有真正试图展示它。

If you call app.setVisible(true) it will display, and the call will block. 如果您调用app.setVisible(true) ,它将显示,并且调用将被阻止。

You need to call setVisible(true) on your Test instance. 您需要在Test实例上调用setVisible(true)。 It's also best to run this code in another thread. 最好在另一个线程中运行此代码。

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Test app = new Test();
            app.setVisible(true);
        }
    }
}

Add this line at the end of your constructor: 在构造函数的末尾添加以下行:

setVisible(true);

Otherwise the JFrame never gets shown and the program exits. 否则, JFrame永远不会显示,程序退出。 You might want to uncomment the setDefaultCloseOperation bit as well - although that is unrelated to your problem. 您可能还想取消注释setDefaultCloseOperation位 - 尽管这与您的问题无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM