gpt4 book ai didi

java - 将逻辑类链接到我的 gui 类 java

转载 作者:行者123 更新时间:2023-12-01 11:31:19 24 4
gpt4 key购买 nike

你好,我想知道如何将我的逻辑类链接到我的 gui 类?我写了一个逻辑类,它是结构,然后必须给它一个接口(interface);所以我编写了另一个类,即 gui 类,但不知道如何使 GUI 类从逻辑类中获取变量。P.S:这是一个猜数字游戏,用户必须猜出 1-10 之间的数字。

逻辑类

import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

public class GG {


public static void main(String[] args)
{
//random number
Random rand = new Random();
int answer = rand.nextInt(10) +1;
int guess = 0;
int attempts = 0;
public

//user's guess

Scanner keyboard = new Scanner(System.in);


GuessingGameGui gui = new GuessingGameGui();
gui.setVisible(true);


while(answer != guess)
{
try
{

System.out.print("Guess a number between 1 and 10: ");
attempts++;
guess = keyboard.nextInt();
if (guess < 1 || guess > 10)
//throw new BadGuessException()
throw new BadGuessException("invalid entry (" + attempts + " attempts so far)");
}
catch (BadGuessException e)
{
System.out.println(e.getMessage());
}
catch (InputMismatchException e)
{
System.out.println("Please enter integers only, and try again");
keyboard.next(); //to get rid of infinite loop issue
}
}

System.out.println("YOU GOT IT (" + attempts + "attempts )");

}

}

GUI 类

public class GuessingGameGui extends JFrame {

public GuessingGameGui() {

final int WINDOW_WIDTH = 650; // Window width in pixels
final int WINDOW_HEIGHT = 250; // Window height in pixels

setTitle("Guessing Game");

setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JPanel north = new JPanel();
JLabel lab1 = new JLabel("Guess a number between 1 and 10?");
setLayout(new FlowLayout());
north.add(lab1);
add( north );

JPanel center = new JPanel();

final JTextField titleText = new JTextField();
titleText.setPreferredSize( new Dimension( 200, 24 ) );
setLayout(new FlowLayout());

JButton button = new JButton("Guess");
Action action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
String typed = titleText.getText();
int guess = Integer.parseInt(typed);
}
};

titleText.addActionListener( action );

button.addActionListener( action );
center.add(titleText);
center.add(button);
add( center );

JPanel south = new JPanel();
JLabel lab2 = new JLabel("YOU GOT IT " + attempts);
south.add(lab2);
add( south );

}

}

最佳答案

一种常见的方法是将逻辑对象添加到 GUI,例如通过构造函数。然后,每当 GUI 上发生某些情况时,您都需要在逻辑对象上调用正确的方法,并根据需要更新显示。

关于java - 将逻辑类链接到我的 gui 类 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30360860/

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