2017-11-19 1 views
0

변경 사항을 유지하면서 내 actionPerformed 외부의 (배수) 퍼센티지 변수에 액세스하려고합니다. 드롭 다운 메뉴이며 확인 버튼을 누릅니다. 한번 누르면 백분율 값이 계산되어 나중에 프로그램에서 사용하고 싶습니다. 여기 JAVA - 클래스 외부에서 수행 한 동작 내부에서 변수를 사용하려고 시도했습니다.

코드의 조각입니다 :
btn.addActionListener(
new ActionListener(){ 
    public void actionPerformed(ActionEvent e){ 

    String currentCountry = (String)cb.getSelectedItem(); 
    double percentage = 0.00; 

     if(currentCountry.equals("Brazil") || currentCountry.equals("Argentina")) { 
      cb2.removeAllItems(); 
      for(int i = 0; i < choicesSouthAmerica.length; i++) { 
       cb2.addItem(choicesSouthAmerica[i]); 
      } 
     } 

     else { 

      cb2.removeAllItems(); 
      for(int i = 0; i < choicesEurope.length; i++) { 
       cb2.addItem(choicesEurope[i]); 
      } 
     } 

    btn.setEnabled(false); 
    btn2.setEnabled(true); 

     if(currentCountry.equals("Brazil") || currentCountry.equals("Argentina")){ 
       percentage = 1/5; 
       System.out.println(percentage); 
      } 
     else{ 
       percentage = 1/8; 
       System.out.println(percentage); 
      } 
     } 
    } 

); 

친절하게 해 주셔서 감사합니다

+1

문제를 보여주는 완전한 최소 예제 ** ** 제대로 들여 쓰기 **를 게시하십시오. 그것이해야 할 일과 대신하는 일을 설명하십시오. –

+0

들여 쓰기가 왜 그렇게 밝혀 졌는지 알지 못합니다. 붙여 넣기를 시도하고 Ctrl 키를 사용하여 들여 쓰려고했지만 대신이 방법이 나타났습니다. 이 메서드 외부에서 double percentage 변수를 어떻게 사용할 수 있는지 궁금합니다. – Brow

+0

그리고 내가 게시 한 코드에 얼마나 많은 메소드가 있는지, 그리고 변수가 선언 된 곳이 궁금 해서요. 코드가 제대로 들여 쓰기가 안되기 때문에 알아낼 수 없습니다. –

답변

0

실제로 필요한 것은 정적 필드 일뿐입니다 (액세스 수정자를 모두 가질 수 있음). 그래서 이런 식으로 뭔가해야한다고 생각합니다.

public class Test { 

     static double d = 0; 

     public static void main(String[] args) { 
      JButton b = new JButton("ASDF"); 
      b.addActionListener(new ActionListener(){ 
       @Override 
       public void actionPerformed(ActionEvent arg0) { 
        d = 5; 
       } 

      }); 
     } 
    } 
+0

감사합니다. 그게 지금 일 했어! – Brow

+0

@newbievancouver 당신이 내 대답을 좋아한다면 그것을 받아 들인 것으로 플래그하는 것을 잊지 마십시오. – JAAAY

1

당신이 getClientProperty와 putClientProperty (Object, Object)를 사용하여 및 getClientProperty를 (Object)을 다음과 같은 기능을 사용할 수 있습니다

JButton btn = new JButton("Ok"); 
    btn.putClientProperty("percentage",1.0);//or whatever initial value 
    btn.addActionListener(arg0 -> { 
     JButton source = (JButton) arg0.getSource(); 
     double per = (double)source.getClientProperty("percentage"); 
     per = (double)10/8; 
     source.putClientProperty("percentage",per); 
    }); 
    double percentage = (double)btn.getClientProperty("percentage");//or use it in any other object that has access to the btn object 
1

슬프게도 Java는 클로저를 지원하지 않으므로 익명의 클래스 범위를 벗어나는 변수를 수정할 수 없습니다.

class Percentage { 
    double p; 
} 
final Percentage p = new Percentage(); 

btn.addActionListener(
    new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      // [...] 
      p.p = 1/5; 
      // [...] 
     } 
    } 
); 

그런 다음 당신은 당신의 익명 클래스의 p.p 외부를 통해 업데이트 된 비율에 액세스 할 수 있습니다 : 당신이 뭔가를 할 수있는 원칙 있도록하지만, 최종 변수에 액세스 할 수 있습니다. (Btw. 실제로 "백분율"또는 실제로 비율입니까?)

그러나 자바에서는 그다지 관용적이지 않으므로 깨끗한 솔루션은 개인 인스턴스 변수로 적절한 클래스를 만드는 것일뿐입니다. getter를 사용하고 익명 클래스 대신이 메서드를 사용하십시오.

관련 문제