【问题标题】:How to get conditionally assigned value from another class如何从另一个类中获取有条件赋值
【发布时间】:2016-09-27 16:54:39
【问题描述】:

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

@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);
                                    }

现在,这就是我第一个调用的课程(名为 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
        }

    }

【问题讨论】:

    标签: java class if-statement jframe jpanel


    【解决方案1】:

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

    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
    

    更新:

    因此,您似乎想将 Quest 课程的分数/失败传回原来的课程。您可以通过为您的 Quest 类添加一些分数和失败的访问器方法来做到这一点。

    public int getScores(){ 
           return scores;
    }
    
    public int getFails(){
           return fails;
    }
    

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

    new Quest1(); 
    

    任务需要存储在诸如分数之类的变量中并且失败,否则它将被垃圾收集器丢弃。添加一个变量,将当前任务置于顶部,然后在切换任务时将它们换掉。

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

    更新:按钮标志

    您可以通过添加布尔变量来添加标志以检查是否发生了事情。在这种情况下,您可以在初学者课程中使用 Quest1-5 标志。当用户点击类时,您可以将其更改为 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?

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

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

    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)
    

    在您的初学者课程中:

    //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() 方法(可以是任何时间,但在您的情况下,当您完成逻辑时调用它)。

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

    【讨论】:

    • 是的,这是因为我不知道您在要将信息传递到的类中的名称和方法。您需要将“otherclass”替换为您尝试将信息发送到的任何类,并且“process”可以替换为将使用您想要传递的分数和失败值的任何方法。
    • 是的。用你需要的尽可能多的信息更新它,我会更新我的答案以更好地帮助你。
    • @Presh_K7 通常对于游戏来说,他们会有一个叫做“标志”的东西,这是一个可以用来检查是否满足条件的变量。在这种情况下,您可以创建布尔标志来指定是否单击了按钮。这可以属于按钮本身,也可以作为单独的变量,然后创建一个方法,将遍历所有按钮并检查是否所有标志都打开。
    • 您必须将它们放置在程序中的逻辑点。一种这样的解决方法是在每个任务完成后调用您的 checkQuest() 触发器。 (也许在你的听众里面)
    • 对不起,应该是无效的。我是我的错字,我会修复错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多