我正在用Java制作一个多选游戏。当用户按下图片上的播放时,屏幕变为问题所在的图片。我想在JFrame上显示多个选项,但由于某种原因,我的代码无法正常工作,也没有显示多个选项。此外,我还有另一个关于java的问题。如何使用我的JButtons设置正确的答案?
public class myWork extends JPanel implements MouseListener{
int screen;
Image homeScreen, question1;
ButtonGroup group1 = new ButtonGroup();
private JRadioButton q1a1;
private JRadioButton q1a2;
private JRadioButton q1a3;
private JRadioButton q1a4;
public myWork() {
screen = 1;
JFrame frame = new JFrame ("Quiz UP!");
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setVisible(true);
frame.add(this);
//Below are all of the pictures which will be used for this game
homeScreen = Toolkit.getDefaultToolkit().getImage("homeScreen.PNG");
question1 = Toolkit.getDefaultToolkit().getImage("question1.PNG");
frame.setVisible(true);
addMouseListener(this);
}
public void G1 () {
q1a1 = new JRadioButton ("Doe Doe Bird", false);
q1a2 = new JRadioButton ("Dove", false);
q1a3 = new JRadioButton ("Female Deer", true);
q1a4 = new JRadioButton ("Deer", false);
//Add the radiobuttons on the screen
JFrame frame = new JFrame ();
frame.add(q1a1);
frame.add(q1a2);
frame.add(q1a3);
frame.add(q1a4);
//Group for buttons
//The group makes it so when one button is checked, the other ones are turn off
group1 = new ButtonGroup();
group1.add(q1a1);
group1.add(q1a2);
group1.add(q1a3);
group1.add(q1a4);
JPanel panel = new JPanel();
panel.add(q1a1);
panel.add(q1a2);
panel.add(q1a3);
panel.add(q1a4);
setVisible(true);
}
public void paintComponent(Graphics g)
{
if (screen == 1) {
g.drawImage (homeScreen, 0,0,600,600,this);
}else if (screen == 2) {
g.drawImage(question1, 0, 0, 600, 600, this);
G1();
}
}
public void mouseClicked (MouseEvent e)
{
int x, y;
x = e.getX ();
y = e.getY ();
if ((x<=373 && x >=223) && (y<=410 && y >=327)) {
screen = 2;
repaint();
}
}
public void mouseReleased (MouseEvent e)
{
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public static void main (String [] args) {
myWork work = new myWork();
}
}
发布于 2018-12-13 14:17:28
我认为问题是你正在创建一个新的JFrame并将复选框添加到新的JFrame中。但您可能想要做的是将复选框添加到JPannel(this)。或者,如果您真的想要创建一个新的JFrame,则需要显示它。添加frame.setVisible(true);
到G1()的末尾。
另外,我建议您遵循Java编码约定。我个人会推荐Google Style Guide或Oracle Code Convention。
类名应该以大写字母开头,并遵循驼峰案例表示法。所以称之为MyWork。方法名称应以小写字母开头,并使用驼峰大小写表示法。
这有助于使代码更易于阅读和理解。
https://stackoverflow.com/questions/-100003064
复制相似问题