我正在制作一个猜猜你的号码游戏,但它不会运行,只是说它终止了。
还需要有关整体代码的更多帮助
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 :(得分:2)
看起来好像忘记了让窗口可见。这可以通过以下方式完成:setVisible(true);
如果窗口不可见,事件侦听器将无法启动,并且由于没有其他代码可以执行,程序将结束。