2016-09-27 1 views
0

두 개 이상의 클래스에서 조건부로 할당 된 값을 사용하는 데 문제가 있습니다. 조건이 충족되는 경우에만 한 클래스의 값 사용을 적용한 다음 일부 다른 클래스에서 값을 합하여 총 점수를 합산합니다. 이건 내 코드 야!다른 클래스에서 조건부로 할당 된 값을 얻는 방법

@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

귀하의 점수 모양과 리스너 이벤트 내에서 지역 변수를하는 실패 할 것입니다. 도움말 클래스에 인스턴스 변수를 만들면 리스너 내에서 인스턴스 변수를 업데이트 할 수 있지만 프로그램이 실행되는 동안 인스턴스 변수를 유지 한 다음 필요에 따라 생성자 매개 변수로 더 많은 클래스에 전달할 수 있습니다. 청취자

내부 그리고

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 클래스에서 실패 할 수 있습니다.

public int getScores(){ 
     return scores; 
} 

public int getFails(){ 
     return fails; 
} 

이렇게하면 필요할 때 값을 가져올 수 있습니다. 당신이 만든 퀘스트 객체에서 간단하게 호출 할 수 있습니다. 그러나

new Quest1(); 

탐구 점수와 같은 변수에 저장해야하고 실패 그렇지 않으면 멀리 가비지 컬렉터에 의해 던져지는 것입니다 ... 또 다른 문제가있다. 현재 퀘스트를 보유 할 변수를 추가 한 다음 퀘스트를 전환 할 때이를 바꿉니다.

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?

당신이 당신의 프로그램을 구현할 수있는 방법입니다.Q1 완료의 코드는, 그것이를 호출 할 때

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

무슨 일이 끝나는 것은 : 당신의 초급 클래스 내부

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) 

: 당신의 퀘스트 내부

는 인터페이스에 대한 인터페이스와 변수를 포함 callBack() 메서드 (언제든지 사용할 수 있지만 논리가 끝나면 호출 할 수 있습니다).

초보자 클래스는 해당 메서드가 호출 될 때 수행해야 할 작업을 Q1에 알려주는 코드를 전달합니다.

+0

나는 그것에 약간의 코드가 필요하다! –

+0

코드 논리는 괜찮은 것 같지만 .... 적용하는데 어려움이 있습니다! .... 세 번째 코드 조각은 otherclass.process (점수, 실패)를 읽습니다. 적용 할 때 오류가 발생합니다! 나는 이미 점수를 만들었고 각 반에서 실패했지만, 효과가 없습니다! –

+1

네가 정보를 전달하고자하는 수업에서 내가 가진 이름과 방법을 모르겠다. "otherclass"를 정보를 전송하려는 클래스로 바꿔야하며, "처리"는 점수 및 실패 값을 사용하여 전달할 방법으로 대체 할 수 있습니다. – Brion

관련 문제