【问题标题】:Running a program again on button click?单击按钮再次运行程序?
【发布时间】:2020-10-25 03:16:17
【问题描述】:

所以我需要程序做的是在 dialogResult 为 0(是选项)时重新生成一个新的随机数 (Zahl)。我认为重新启动程序将是实现这一目标的一种方法。我尝试使用 System.exit(0) 关闭 JFrame,然后将可见性设置为 true (f.setVisible(true))。那没有用,框架没有重新出现。我也试过SwingUtilities.updateComponentTreeUI(f);f.revalidate();f.repaint(),一个都没有工作。

还有其他方法可以“重新加载”JFrame,还是只生成一个新的随机数会更好?

提前致谢!

import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.util.Random;
    
    public class Zahlenraten{
        static int i = 0;
        public static void main(String[] args) {
            
            JFrame f = new JFrame("Zahlenraten");
            f.setSize(500,500);
            //f.setLayout(null);
            
            JTextField t = new JTextField("");
            t.setBounds(95,10,150,30);
            f.addWindowFocusListener(new WindowAdapter() {
             
                public void windowGainedFocus(WindowEvent e) {
                    t.requestFocusInWindow();
                }
            });
            
            
            JButton e = new JButton("Exit");
            e.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                System.exit(0);
                }
            });
            e.setBounds(300, 100, 100, 30);
            
            JLabel txt = new JLabel("Zahl eingeben:");
            txt.setBounds(10,10,150,30);
            
            Random r = new Random();
            int Zahl = r.nextInt(100-0+1);
            
            
            
            JButton b = new JButton("Prüfen");
            f.getRootPane().setDefaultButton(b);//Enter Key = button b
            b.addActionListener(evt -> { //statt evt könnte man natürlich auch actionPerformed... nehmen.
                 i++;
                 
                 String str = t.getText();
                 int wert = Integer.parseInt(str);
                 t.setText("");
                 
                 if(wert > Zahl) {
                     System.out.println("Der gesuchte Wert ist kleiner.");
                 }
                 if(wert < Zahl) {
                     System.out.println("Der gesuchte Wert ist größer.");
                 }
                 if(wert == Zahl) {
                     System.out.println("Der gesuchte Wert wurde gefunden! Du hast "+i+" Versuche gebraucht.");
                     int dialogResult = JOptionPane.showConfirmDialog(null, "Wollen Sie noch eine Runde spielen?","Frage",JOptionPane.YES_NO_OPTION);
                     if(dialogResult==0) {
                         
                     }else {
                         System.exit(0);
                     }
                 }
            });
            b.setBounds(10,100,100,30);
            
            JPanel p = new JPanel();
            p.setLayout(null);
            p.add(b);
            p.add(e);
            p.add(t);
            p.add(txt);
            f.add(p);
            f.setVisible(true);

            
        }
    }

【问题讨论】:

  • 如果您能给我们提供完整的代码,我们可以复制它,然后测试代码会更容易
  • 哦,我没有注意到代码不完整。我正确更新了它。

标签: java swing jframe reload


【解决方案1】:

目前,您的方法就像是在您想要反转方向时关闭汽车引擎——这种方法显然是不必要的,因为您可以在不重新启动汽车的情况下换档。

您需要将逻辑和 UI 分成两个单独的类。将您的 UI 视为遥控器,将包含逻辑的类视为执行从 UI 接收的命令的引擎。您的 UI 类会创建引擎类的实例。

引擎类运行一个游戏循环,该循环继续运行直到您告诉它停止,所以在编程术语中,您的程序具有状态:游戏正在进行中,或者游戏不在进展。

boolean imGange = true;
boolean ratenFalsch = true;

while(imGange)
{
    // generate random number
    
    while(ratenFalsch)
    {
        // ask for a guess
        // if the guess is correct
            // print message: right
            ratenFalsch = false;
        // if the guess is incorrect
            // print message: wrong
    }
    // ask user to play again
    // if no
        imGange = false; // game will end, but the program will still be running
}

在构建 UI 之前,请确保您的引擎正常运行并且您可以通过控制台玩游戏。当游戏正常运行时,您必须将 UI 中的按钮映射到引擎中的方法。例如,您的 UI 有一个按钮“Neu Spiel”,它从引擎调用相应的方法,例如 mainLoop(),其中我上面概述的所有逻辑都包含在名为 mainLoop 的方法中。

以这种方式组织您的代码意味着只要您的用户界面在运行,您的引擎就在运行。使用主循环意味着您可以随时开始新游戏,而无需停止和启动 UI,并且每次游戏都会获得一个新的随机数。

【讨论】:

  • 您非常有帮助,非常感谢!您不仅解决了我的问题,还向我解释了如何用这些简单的轮廓组织游戏结构。我将来可以用它来创建类似的程序。感谢您的详细回复。
  • 我很高兴您认识到这种模式可以扩展到您拥有 UI 的任何其他情况。 Freundliche Gruesse!
  • @aren pi:MarsAtomic 使用的通用模式称为model / view / controller 模式。
猜你喜欢
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-13
  • 2016-11-03
  • 1970-01-01
  • 2020-09-21
相关资源
最近更新 更多