这是我的代码,我正在尝试为学校做一个项目,但是当我添加一个循环导致第二个JFrame完全变黑时,它不能用于某种奇怪的原因。 一旦点击按钮,它应该在按钮A B和C之间切换
答案 0 :(得分:2)
对你的意图进行一些猜测,你只是想以线性的方式思考,就像你对基于控制台的应用程序一样,但GUI是一个事件驱动的环境。有些事情会发生,你会被告知,你会做出反应。
基本上,在您准备好基础IU后,您应该最后致电setVisible
。
你需要摆脱你的while-loop
,它不会做你想做的事。相反,您需要使用单个ActionListener
,它可以根据x
的值确定单击任何按钮时应该发生的情况,例如:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class Game implements Runnable {
public static void main(String[] args) {
EventQueue.invokeLater(new Game());
}
private int counter;
private int x;
@Override
public void run() {
// TODO Auto-generated method stub
counter = 0;
JFrame y = new JFrame("Game");
y.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton start = new JButton("Start game");
y.add(start, BorderLayout.SOUTH);
y.pack();
JLabel a = new JLabel();
a.setText("<HTML><body><H1>Instructions</H1><p>Click the 'start' button to start the game" + "<br>Click as many of the red buttons as you can before time runs out!<p></body></HTML>");
y.add(a);
y.pack();
y.setVisible(true);
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Timer time = new Timer(10000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("You got " + counter + " points");
System.exit(0);
}
});
time.start();
JFrame z = new JFrame("Sequence game");
FlowLayout fl = new FlowLayout(0, 50, 40);
z.getContentPane().setLayout(fl);
JButton a = new JButton("A");
Font f = a.getFont();
Font myFont = f.deriveFont(Font.BOLD, f.getSize() * 4);
a.setSize(200, 100);
a.setVisible(true);
JButton b = new JButton("B");
b.setVisible(true);
b.setSize(200, 100);
JButton c = new JButton("C");
c.setVisible(true);
c.setSize(200, 100);
z.setSize(1280, 1024);
z.getContentPane().add(a);
z.getContentPane().add(b);
z.getContentPane().add(c);
Random r = new Random();
x = r.nextInt(3);
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (x == 0 && e.getSource().equals(a)) {
counter++;
x = r.nextInt(3);
a.setFont(f);
} else if (x == 1 && e.getSource().equals(b)) {
counter++;
x = r.nextInt(3);
b.setFont(f);
} else if (x == 2 && e.getSource().equals(c)) {
counter++;
x = r.nextInt(3);
c.setFont(f);
}
switch (x) {
case 0:
a.setFont(myFont);
break;
case 1:
b.setFont(myFont);
break;
case 2:
b.setFont(myFont);
break;
}
z.revalidate();
z.repaint();
}
};
System.out.println(x);
switch (x) {
case 0:
a.setFont(myFont);
break;
case 1:
b.setFont(myFont);
break;
case 2:
b.setFont(myFont);
break;
}
z.revalidate();
z.repaint();
a.addActionListener(listener);
b.addActionListener(listener);
c.addActionListener(listener);
z.pack();
z.setVisible(true);
}
});
}
}