gpt4 book ai didi

java - 如何让 Gui 真正提示对话框?

转载 作者:行者123 更新时间:2023-11-30 03:43:39 25 4
gpt4 key购买 nike

所以我试图理解 Java 中 Gui 的使用,并通过猜数字游戏来做到这一点。它编译正确,但是当我运行该程序时,它只显示带有“恭喜你获胜!”的框架。在顶部。我的主要问题是为什么对话框根本不弹出以及我应该做什么来解决这个问题。相关说明,当我的代码为 JOptionPane.showInputDialog(this,"Play Again? Y/N") 时,我收到错误消息“非静态变量不能从静态变量引用”语境。”我的第二个也是不太重要的问题是如何使消息垂直和水平位于框的中心。

    import javax.swing.*;
import java.awt.*;
import java.util.Scanner;

public class RandomNumberGame{
public static JLabel higherThan;
public static JPanel tooHigh;
public static JLabel lowerThan;
public static JPanel tooLow;
public static JPanel exactlyCorrect;
public static JLabel correctAnswer;
public static JFrame guiFrame;
public static void main(String[] args){
RandomFun();
}
public static void RandomFun()
{
Scanner input=new Scanner(System.in);
guiFrame = new JFrame();


guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Fun Games!");
guiFrame.setSize(500,500);
guiFrame.setLocationRelativeTo(null);
guiFrame.setVisible(true);


final JPanel tooHigh = new JPanel();
higherThan = new JLabel("Too High!");
final JPanel tooLow = new JPanel();
lowerThan = new JLabel("Too Low!");
final JPanel exactlyCorrect = new JPanel();
correctAnswer = new JLabel("Congratulations, you won!");

tooHigh.add(higherThan);
tooLow.add(lowerThan);
exactlyCorrect.add(correctAnswer);
guiFrame.add(tooHigh, BorderLayout.CENTER);
guiFrame.add(tooLow, BorderLayout.CENTER);
guiFrame.add(exactlyCorrect, BorderLayout.CENTER);
}
public static void GuessNumber(){
String again;
String lastGuess = "0";
boolean moreGame=true;
int lastGuessInt = Integer.parseInt(lastGuess.toString());
int winner = (int) (Math.random()*999+1);
while(moreGame){
lastGuess = JOptionPane.showInputDialog("Guess a Number");
if(winner < lastGuessInt){
tooHigh.setVisible(true);
tooLow.setVisible(false);
exactlyCorrect.setVisible(false);
}
else if(winner > lastGuessInt){
tooHigh.setVisible(false);
tooLow.setVisible(true);
exactlyCorrect.setVisible(false);
}
else{
tooHigh.setVisible(false);
tooLow.setVisible(false);
exactlyCorrect.setVisible(true);
moreGame=false;
}
}
again = JOptionPane.showInputDialog("Play again? Y/N");
switch(again){
case "y": case "Y":
GuessNumber();
break;
case "n": case "N":
System.exit(0);
break;
}
}
}

最佳答案

为什么会出现“不当行为”:

  • 您的主方法调用RandomFun()
  • 然后 RandomFun() 创建一个 JFrame 并显示。
  • 它在 BorderLayout.CENTER 位置添加了 3 个 JPanel 全部!
  • 因此,只会显示最后一个 JPanel,因为它将根据 BorderLayout 记录的行为覆盖所有之前添加的 JPanel。
  • 因此,您的代码的行为完全符合您的预期。
  • 其他问题包括过度使用 static 修饰符、添加所有组件之前在 JFrame 上调用 setVisible(true)、设置 JFrame 的大小、创建一个方法 GuessNumber() ,该方法永远不会被可行的运行代码调用,代码不遵守 Java 命名约定(方法和字段应以小写字母开头,类应以大写字母开头) ),...

如果我处在你的位置,我会把 GUI 编码放在一边,因为我首先想集中精力学习 Java 基础知识,包括避免所有静态方法和字段,而是创建真正的 OOP 兼容类,因为在深入研究 GUI 编码之前,这种理解至关重要。只需几周的学习就足以让您足够强大,然后尝试一些 Swing 编码。

<小时/>

我尝试创建一个猜谜游戏程序:

import java.awt.BorderLayout;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.text.JTextComponent;

@SuppressWarnings("serial")
public class RandomNumberGame2 extends JPanel {
private static final int LOW = 0;
private static final int HIGH = 100;
public static final String START_GAME = "Please guess the random number between "
+ LOW + " and " + HIGH;
public static final String TO_HIGH = "Your guess is too high. Please try again";
public static final String TO_LOW = "Your guess is too low. Please try again";
public static final String CONGRATS_YOU_WIN = "Congratulations, you win!!!";

private Random random = new Random();
private int randomNumber; // holds the randomly selected number
private JTextField inputField = new JTextField(5); // where user enters guess
private JButton submitButton = new JButton(new SubmitAction("Submit", KeyEvent.VK_S));
private JButton resetButton = new JButton(new ResetAction("Reset", KeyEvent.VK_R));
private JLabel statusLabel = new JLabel(START_GAME, SwingConstants.CENTER);

public RandomNumberGame2() {
// so field will select all when gains focus
inputField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
JTextComponent textComp = (JTextComponent) e.getSource();
textComp.selectAll();
}
});
// so input field will submit number if enter is pressed
inputField.addActionListener(submitButton.getAction());

JPanel centerPanel = new JPanel(); // uses flow layout by default
centerPanel.add(new JLabel("Enter number here:"));
centerPanel.add(inputField);
centerPanel.add(submitButton);
centerPanel.add(resetButton);

setLayout(new BorderLayout());
add(statusLabel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);

resetGame();
}

public void resetGame() {
randomNumber = random.nextInt(HIGH - LOW) + LOW;
inputField.setText("");
statusLabel.setText(START_GAME);
inputField.requestFocusInWindow();
inputField.selectAll();
}

private class SubmitAction extends AbstractAction {
public SubmitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}

@Override
public void actionPerformed(ActionEvent e) {
try {
int input = Integer.parseInt(inputField.getText().trim());
if (input > randomNumber) {
statusLabel.setText(TO_HIGH);
} else if (input < randomNumber) {
statusLabel.setText(TO_LOW);
} else {
statusLabel.setText(CONGRATS_YOU_WIN);
}
inputField.requestFocusInWindow();
inputField.selectAll();

} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(RandomNumberGame2.this,
"Please enter only integer data", "Non-numeric Data Error",
JOptionPane.ERROR_MESSAGE);
inputField.setText("");
}
}
}

private class ResetAction extends AbstractAction {
public ResetAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}

@Override
public void actionPerformed(ActionEvent e) {
resetGame();
}
}

private static void createAndShowGui() {
RandomNumberGame2 mainPanel = new RandomNumberGame2();

JFrame frame = new JFrame("Fun Games 2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

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

关于java - 如何让 Gui 真正提示对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26269922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com