如何从另一个 class 获取有条件分配的值

How to get conditionally assigned value from another class

我在多个 class 中使用条件赋值时遇到一些问题。当且仅当满足条件时,我想在一个 class 中应用一个值,然后在其他 class 中使用它来加总分。这是我的代码!

@SuppressWarnings("serial")
public class Beginner extends JPanel {

    static JButton quest;
    Random rand = new Random();

    int n = 10;

    static List <Point> points = new ArrayList<Point> ();

    int scores;
    int fails;

    public Beginner() {

              int radius = 200;
              Point center = new Point (250, 250);

              double angle = Math.toRadians(360 / n);

              points.add(center);

              for (int i = 0; i < n; i++) {
                  double theta = i * angle;

                  int dx = (int) (radius * Math.sin(theta));

                  int dy = (int) (radius * Math.cos(theta));

                  Point p = new Point (center.x + dx , center.y + dy);

                  points.add(p);

              }

              draw (points);
              }

               public void draw (List<Point> points) {

                   JPanel panels = new JPanel();

                   SpringLayout spring = new SpringLayout();

                   int count = 1;
                   for (Point point: points) {

                       quest = new JButton("Question " + count);
                       quest.setForeground(Color.BLACK);
                        Font fonte = new Font("Script MT Bold", Font.PLAIN, 20);
                        quest.setFont(fonte);

                       add (quest);
                       count++;

                       spring.putConstraint(SpringLayout.WEST, quest, point.x, SpringLayout.WEST, panels );

                       spring.putConstraint(SpringLayout.NORTH, quest, point.y, SpringLayout.NORTH, panels );

                       setLayout(spring);

                       panels.setOpaque(false);
                       panels.setVisible(true);
                       panels.setLocation(5,5);

                       add(panels);

                        quest.addActionListener(new java.awt.event.ActionListener(){
                            @Override
                            public void actionPerformed (ActionEvent p) {   

                                if (point.equals(points.get(0))) {

                                    new Quest1();

                                    JButton source = (JButton) p.getSource();
                                  source.setEnabled(false);
                                  source.setBackground(Color.GREEN);

                                }   
                               else if (point.equals(points.get(1))) {

                                    new Quest2();

                                     JButton source = (JButton) p.getSource();
                                        source.setEnabled(false);
                                        source.setBackground(Color.GREEN);
                                                        }
                               else if (point.equals(points.get(2))) {

                                       new Quest3();

                                   JButton source = (JButton) p.getSource();
                                  source.setEnabled(false);
                                  source.setBackground(Color.GREEN);

                                                       }
                             else if (point.equals(points.get(3))) {

                                    new Quest4();

                                    JButton source = (JButton) p.getSource();
                                   source.setEnabled(false);
                                   source.setBackground(Color.GREEN);
            }

            else if (point.equals(points.get(4))) {

                new Quest5();

                JButton source = (JButton) p.getSource();
              source.setEnabled(false);
              source.setBackground(Color.GREEN);
                                    }

现在,这就是我的第一个 class(名为 Quest1)的样子

    public class Quest1 {
        //sound files to be shuffled and played!
        String [] word = { "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/audio.wav",
                "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/bomb.wav",
                "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/baby.wav",
                "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/gym.wav",
                "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/hearing.wav",
                "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/goal.wav",
                "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/manifest.wav",
                "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/mountain.wav",
                "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/market.wav",
                "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/debate.wav",
                "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/election.wav",
                "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/number.wav",
        };
        //matching strings for each file
        String [] words = { "Audio", "Bomb", "Baby", "Gym", "Hearing", "Goal", "Manifest","Mountain", "Market", "Debate", "Election", "Number" };

        Random rand = new Random();
        int random = rand.nextInt(word.length);
        String temp = word[random];

        int scores;
        int fails;


        public Quest1 () {

           //announcing the JComponents to be used
            JFrame frame =  new JFrame ();
            JButton click = new JButton("Play");
            JTextField type = new JTextField(15);
            JLabel pic = new JLabel(new ImageIcon("C:\Users\HP\Desktop\Sample pics\1.png"));
            JButton score = new JButton ("Check My Answer");
            JPanel cont = new JPanel ();

            //set up frame properties
            frame.getContentPane().setBackground(Color.WHITE);
            frame.setLayout(new FlowLayout());
            frame.setUndecorated(true);                             
            frame.setResizable(false);
            frame.setSize(500,500);
            frame.setLocationRelativeTo(null);
            frame.add(cont, BorderLayout.CENTER);
            frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
           frame.setVisible(true);

           //setting layout of JPanel
            cont.setLayout(new GridBagLayout());
            cont.setOpaque(false);
            cont.setPreferredSize(new Dimension(500,500));
            cont.setLocation(100, 50);
            GridBagConstraints g = new GridBagConstraints();
            g.anchor = GridBagConstraints.WEST;
            g.gridx = 4;
            g.gridy = 2;
            g.gridwidth = 2;
            g.insets = new Insets (70, 2, 2, 2);
            cont.add(pic , g);


            g.anchor = GridBagConstraints.WEST;
            g.gridx = 4;
            g.gridy = 5;
            g.gridwidth = 2;
            g.insets = new Insets (50, 2, 2, 2);
            cont.add(click, g);


            click.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent e) {
                        //sound file shuffled and played
                    }
            });
                   g.anchor = GridBagConstraints.EAST;
                   g.gridx = 10;
                   g.gridy = 4;
                   g.gridwidth = 5;
                   g.insets = new Insets(30, 2, 2, 10);
                   Font fonty = new Font("Lucida", Font.PLAIN, 15);
                   type.setFont(fonty);
                   cont.add(type, g);

                   g.anchor = GridBagConstraints.SOUTH;
                   g.gridx = 9;
                   g.gridy = 8;
                   g.gridwidth = 2;
                   g.insets = new Insets(2, 2, 2, 50);
                   cont.add(score, g);

                   score.addActionListener(new ActionListener(){
                       public void actionPerformed (ActionEvent tx) {

                          if (type.getText().equals(words[random])) {

                             //sound file played
                                    scores+= 3;
                                     String a = "Correct!..... The answer is " + words[random];
                              JOptionPane.showMessageDialog(null, a);

                              frame.dispose();
                              return;
                          }

                          else {
                                //sound file played again
                                    fails+=0; 
            // This is where my problem is: The other 10 classes are like 
      //this, I want to get this value and that of scores (depending on the 
      //condition that is met), and add them up in the class beginner! )
                           String a = "Sorry, The Answer is " + words[random];
                           JOptionPane.showMessageDialog(null, a);

            frame.dispose();
                              }   
                          }  
                       });
                  //sound file played
        }

    }

你的分数和失败是侦听器事件中的局部变量。如果您在帮助 class 中创建一个实例变量,您可以在侦听器中更新它们,但只要您的程序是 运行,它们就会持续存在,然后可以传递给更多 classes构造函数参数用于您可能需要的任何目的。

public class help extends JFrame {
        JPanel hold = new JPanel ();
        JTextField enter = new JTextField(10);
        JButton check = new JButton ("Check answer");
        JButton quest = new JButton ("See question");
        JLabel lunch = new JLabel ("Who is the current President of the United States?");

        //Add fields you want to track here
        int scores;
        int fails;

     public help () {

然后在你的听众里面

     scores += 3; //track them anyway you want

更新:

看来您想将 score/fails 从您的任务 class 传回原来的 class。您可以通过为分数添加一些访问器方法来做到这一点,并在您的任务中失败 class.

public int getScores(){ 
       return scores;
}

public int getFails(){
       return fails;
}

这将允许您在需要时检索这些值。您只需在您创建的 Quest 对象上调用它们。但是还有一个问题...

new Quest1(); 

任务需要存储在像分数这样的变量中并且失败,否则它会被垃圾收集器丢弃。添加一个变量,将当前任务保持在顶部,然后在切换任务时将它们换掉。

Quest1 q1;
...
...
q1 = new Quest1();
...
...
scores = q1.getScores();
fails = q1.getFails();

更新:按钮标志

您可以添加标志以通过添加布尔变量来检查是否发生了事情。在这种情况下,您可以在 Beginner class 中设置 Quest1-5 标志。当用户点击 class 时你可以将其更改为 true,然后检查是否所有这些都已完成。

boolean Q1 = false;
boolean Q2 = false;
...

if (point.equals(points.get(0))) { // User clicks quest 1
    Q1 = true;
    ...

...
if (checkQuests()){
    //do stuff if all buttons are clicked
}

...

public boolean checkQuests(){ //cleaner if you use arrays
   if(Q1 == false || Q2 == false || ... Q5== false){
      return false;
   }
   else{
      return true;
   }
}

更新:回调函数

使用 GUI 和侦听器时,并非所有操作都按您希望的顺序发生。 GUI 和事件发生在它们自己的线程上,并且您通常希望在另一个事件结束时触发一个事件。您可以通过使用回调函数来做到这一点。

What is a callback function?

以下是如何在您的程序中实现一个。

在您的任务中包含一个接口和一个接口的变量:

public class Quest{

    CallBack cb;

    interface CallBack{
        public void callBack();
    }

    //add some way to set the call back, such as setter (or use constructor)
    public void setCB(CallBack cb){ this.cb = cb;}

  //Inside the action listener of your quest doing something
  ...
    cb.callBack(); //call the callback method when you are done and want to do your check (it calls the beginner class back)

初学者内心深处class:

//When creating a quest 
  Q1 = new Quest1();
  Q1.setCB(new CallBack{
      public void callBack(){
          CheckQuests(); //this tells the program what to do when it hears back from Q1
      }
  }

最终发生的事情是当 Q1 的代码完成时,它调用 callBack() 方法(它可以是任何时间,但在您的情况下,当您完成逻辑时调用它)。

初学者 class 传入代码,告诉 Q1 在调用该方法时应该做什么。