2011-11-06 83 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); 
     } 
    } 
}