2014-06-08 5 views
-1

나중에 사용할 수 있도록이 유형의 배열에 기존 JRadioButtons을 추가하려고합니다. 나는 이것을 가지고있다 :Java의 배열에 기존 객체 추가

public static javax.swing.JRadioButton jRadioButton1; 
public static javax.swing.JRadioButton jRadioButton2; 
public static javax.swing.JRadioButton jRadioButton3; 
public static javax.swing.JRadioButton jRadioButton4; 
public static javax.swing.JRadioButton jRadioButton5; 
public static javax.swing.JRadioButton jRadioButton6; 
public static javax.swing.JRadioButton jRadioButton7; 
public static javax.swing.JRadioButton jRadioButton8; 

이것은 나의 버튼이다.

public static JRadioButton[] seq = new JRadioButton[8]; 

을 그리고 I는 다음과 같이 배열에서 각 버튼을 할당하려고 : 그럼이 선언

seq[0] = jRadioButton1; 

을하지만이 같은 액세스하려고하면

seq[0].setSelected(true); 

I 널 포인터 예외를 얻는다. 나는 Java에 익숙하지 않으며 이것이이 일을하는 첫 번째 논리입니다. 어떤 제안? 그들이 JRadioButton 객체 새로운 할당 전까지는 null 참조입니다

+0

기본적으로 개체는 명시 적으로 초기화하지 않는 한 'null'로 초기화됩니다. 'JRadioButton' 객체를 사용하기 전에 실제로 초기화 했습니까? – JonK

+0

어느 시점에서든'jRadioButton1 = new JRadioButton()'이라고 말합니까? – christopher

답변

2

정적 JRadioButton 변수 대신 당신이 뭘 하려는지의

jRadioButton1 = new JRadioButton(); 
seq[0] = jRadioButton1; 
seq[0].setSelected(true); // Won't throw 
+0

음, 이제 오류가 발생하지 않지만 seq [0] .setSelected (true)는 작동하지 않습니다 .. – user3719358

+0

라디오 단추가 양식에 표시됩니까? –

+0

예. 어떤 아이디어? – user3719358

0

, 전체 코드를 다시 포맷 :

int buttonsNeeded = 8; 
JRadioButton[] seq = new JRadioButton[8]; 
for(int i=0; i<buttonsNeeded; i++) { 
    seq[i] = new JRadioButton(); 
} 

seq[0].setSelected(true); 

이렇게하면 필요한 배열 이 모든 선언을 필요로하지 않고 각 항목을 초기화합니다. 그리고 내가 의미하는 바를 아는 경우 5-10-1000 버튼에도 잘 작동합니다.