2016-04-28 53 views
-3

我正在猜你的號碼遊戲,但它不會運行,只是說它終止。GuessMyNumber gui將不會運行,需要

還需要對整個代碼

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.Random; 
public class GuessMyNumber extends JFrame { 


    private JTextField textField; 
    public JPanel Mainpanel; 
    public JLabel lblEnterNumberHere; 
    public JLabel lblNewLabel; 
    public JButton btnCheckGuess; 
    public JLabel lblNewLabel_1; 
    Random rand = new Random(); 
    int random = rand.nextInt(100); 
    int cap = 3; 
    int tries = 0; 

    public GuessMyNumber(){ 
     getContentPane().setLayout(null); 

     Mainpanel = new JPanel(); 
     Mainpanel.setBounds(0, 0, 424, 250); 
     getContentPane().add(Mainpanel); 
     Mainpanel.setLayout(null); 

     lblNewLabel = new JLabel("Enter a number between 1-100 "); 
     lblNewLabel.setBounds(126, 11, 153, 14); 
     Mainpanel.add(lblNewLabel); 

     lblEnterNumberHere = new JLabel("Enter number here"); 
     lblEnterNumberHere.setBounds(164, 51, 90, 14); 
     Mainpanel.add(lblEnterNumberHere); 

     textField = new JTextField(); 
     textField.setBounds(174, 76, 86, 20); 
     Mainpanel.add(textField); 
     textField.setColumns(10); 

     btnCheckGuess = new JButton("Check guess"); 
     btnCheckGuess.setBounds(161, 107, 93, 23); 
     Mainpanel.add(btnCheckGuess); 

     lblNewLabel_1 = new JLabel(""); 
     lblNewLabel_1.setBounds(150, 159, 129, 47); 
     Mainpanel.add(lblNewLabel_1); 

     initialize(); 

    } 

    private class ButtonListener implements ActionListener 
    { 
     @Override 
     public void actionPerformed(ActionEvent arg0) 
     { 
      int guess = Integer.parseInt(textField.getText()); 
      if(tries==cap){ 
       lblNewLabel_1.setText("You have guessed too many times."); 
      } 
      else{ 
       tries++; 
       if(guess>random) 
        lblNewLabel_1.setText("Your guess was too high."); 
       else if(guess<random) 
        lblNewLabel_1.setText("Your guess is too low."); 
       else 
        lblNewLabel_1.setText("You are correct."); 
      } 
     } 
    } 

    public static void main(String[] args) 
    { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       new GuessMyNumber(); 
      } 
     }); 
    } 

    private void initialize() 
    { 
     Mainpanel.setPreferredSize(new Dimension(300,300)); 
     // Create labels, buttons, etc. and place them on the window here... 
    } 
} 
+0

問題是什麼? – randominstanceOfLivingThing

+0

什麼是隨機結尾'}'的? – Laurel

+0

Java GUI必須使用不同語言環境中使用不同PLAF的不同OS,屏幕大小,屏幕分辨率等。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 –

回答

2

看來好像你已經忘記了使窗口可見更多的幫助。這可以通過以下方式完成:setVisible(true);

如果窗口不可見,則事件偵聽器將無法啓動,並且由於沒有其他代碼要執行,程序將結束。