您能否使JPanel每次单击按钮时随机生成?

时间:2019-06-27 16:52:37

标签: java swing

基本上刚刚开始使用Eclipse在Java中进行编码,作为我的第一个“严肃”项目,我试图编写一个简单的问答游戏。我已经设置了所有的图形和答案系统,但是如果您单击正确的答案,JPanel会重新启动并出现一个新问题。

我已经尝试了一些在线解决方案,包括一个do / while方法,这被证明是毫无用处的,并调用了main方法(所有代码都在其中)似乎是不可能的。

这是我正在谈论的方法:

public static void main(String []args) throws IOException

{      //这里是我剪掉的不必要的东西

     ImageIcon image = new ImageIcon (Imagetesting.class.getResource(i+".jpg"));
     JLabel label = new JLabel (image);
      JFrame f = new JFrame("Quiz");
      JLabel x1 = new JLabel(question);

      JButton x2 = new JButton(answer1);
         //+ other graphic stuff

         f.getContentPane().add(MyPanel, "Center"); // Paste MyPanel in center
                                // of the contentPane    
         f.setExtendedState(JFrame.MAXIMIZED_BOTH); 
         f.setVisible(true);
         x3.addActionListener(new ActionListener() {

             @Override
             public void actionPerformed(ActionEvent e) {

                 if(answer2.equals("therightanswer")){
                 score = score +1;
                 x1.setText("Right answer Punteggio:"+String.valueOf(punteggio)
                 // what am I supposed to put here?
                 );
              ;
                    }
             }});

那我该怎么办?甚至可以调用main方法使其重新启动吗?我在做错什么吗?

1 个答案:

答案 0 :(得分:0)

您可以将标签传递到actionPerformed函数中,以在答案正确时更改这些对象的值。