2011-11-06 88 views
2
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(); 

    } 

} 

当我在eclipse的ubuntu电脑上运行它时,它的停止(终止)没有任何错误。控制台中也没有错误。并没有语法错误。Java - 这个简单的程序有什么问题?

怎么了?是因为我运行openjdk吗?

回答

3

您正在创建一个Test实例,但仅此而已。你从来没有尝试过显示它。

如果您致电app.setVisible(true)它将显示,并且呼叫将被阻止。

1

在构造函数的末尾添加此行永远不会显示,程序退出。您可能还想取消setDefaultCloseOperation位的注释 - 尽管这与您的问题无关。

2

您需要在Test实例上调用setVisible(true)。最好在另一个线程中运行此代码。

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