如何从另一个类获取有条件指定的值

时间:2016-09-27 16:54:40

标签: java class if-statement jframe jpanel

我在一个以上的课程中使用有条件指定的值时遇到了一些问题。当且仅当条件满足时,我想在一个类中应用值,然后在其他类中使用它来累加总分。这是我的代码!

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

    }

1 个答案:

答案 0 :(得分: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(); 

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

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

更新:按钮标志

您可以通过添加布尔变量来添加标记以检查是否发生了事情。在这种情况下,您可以在Beginner类中使用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在调用该方法时它应该做什么。