我是Java新手,我需要你帮助实现GUI。以下是猜猜游戏代码。它有效。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class GuessGame extends JFrame {
private JTextField guessTextField;
private JLabel introLabel, guessLabel, clueLabel;
private JButton enterB, playAgainB;
private int randomNumber;
public GuessGame() {
super("Guessing Game!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates components
enterB = new JButton("Guess");
playAgainB = new JButton("Quit");
introLabel = new JLabel("I have a number between 1 and 1000.");
guessLabel = new JLabel("Can you guess my number? Please enter your guess:");
clueLabel = new JLabel("");
// comment2 = new JLabel(" ");
guessTextField = new JTextField(5);
//content pane
Container c = getContentPane();
setLayout(new FlowLayout());
//adding component to the pane
c.add(introLabel);
c.add(guessLabel);
c.add(guessTextField);
//c.add(comment2);
c.add(enterB);
c.add(playAgainB);
c.add(clueLabel);
//enterB.setMnemonic('G');
//playAgainB.setMnemonic('Q');
setSize(350, 200);
setLocationRelativeTo(null);
setVisible(true);
//setResizable(false);
initializeNumber();
//creating the handler
GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
enterB.addActionListener(ghandler); // add event listener
QuitButtonHandler qhandler = new QuitButtonHandler();
playAgainB.addActionListener(qhandler);
}
private void initializeNumber() {
randomNumber = new Random().nextInt(1000) + 1;
System.out.println(randomNumber);
}
class QuitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class GuessButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
int getUserInput;
int diff;
int Difference;
try {
getUserInput = Integer.parseInt(guessTextField.getText().trim());
if (getUserInput == randomNumber) {
clueLabel.setText(" Correct!");
}
if (getUserInput > randomNumber) {
clueLabel.setText(" Too High");
} else {
clueLabel.setText(" Too Low");
}
}
catch (NumberFormatException e1) {
clueLabel.setText("Enter a VALID number!");
}
}
}
public static void main(String args[]) {
//instantiate gueesgame object
GuessGame app = new GuessGame();
}
}
但是,窗口的颜色应该变为红色或蓝色。请帮我这个代码。我是Java的新手,也是它的语法。我非常感谢你的帮助。谢谢!
答案 0 :(得分:1)
您可以使用:
current = Integer.parseInt(guessTextField.getText().trim());
if (!firstTime) {
if (getUserInput > previous) {
getContentPane().setBackground(Color.red);
} else {
getContentPane().setBackground(Color.blue);
}
}
其中firstTime
和previous
是类成员变量。
如果遇到previous
,请不要忘记分配getUserInput == randomNumber
。
<强>更新强>
您将背景设置为蓝色两次:
if (getUserInput < randomNumber) {
clueLabel.setText("Too Low");
getContentPane().setBackground(Color.blue); <------ remove this extra call
previous = getUserInput;
}
答案 1 :(得分:1)
代码胜过千言万语.....
if (current_Input > previous) {
c.setBackground(Color.red);
} else {
c.setBackground(Color.blue);
}