2017-11-27 2 views
2

GUI 프로그램을 관리 가능한 클래스로 분류했습니다. JPanel을 확장 할 때 다음 예제 코드가 작동하지만 생성자에서 JPanel 객체를 만들 때 왜 작동하지 않는지 궁금합니다. 누구든지 설명 할 수 있습니까? 이 작동 ->다른 클래스의 프레임에 추가 할 때 왜 JPanel을 확장합니까?

public class SomePanel extends JPanel{ 
private JScrollPane scroll; 
private JTextArea text; 

public SomePanel() { 

    // TextArea 
    text = new JTextArea(10,50); 
    text.setBackground(Color.black); 

    // JScrollPane 
    scroll = new JScrollPane(text); 
    scroll.getHorizontalScrollBar().setEnabled(false); 
    scroll.setWheelScrollingEnabled(false); 

    add(scroll); 
} 

이 작동하지 않습니다 ->

public class SomePanel{ 

private JScrollPane scroll; 
private JTextArea text; 
private JPanel panel; 

public SomePanel() { 

    panel = new JPanel(); 

    text = new JTextArea(10,50); 
    text.setBackground(Color.black); 

    // JScrollPane 
    scroll = new JScrollPane(text); 
    scroll.getHorizontalScrollBar().setEnabled(false); 
    scroll.setWheelScrollingEnabled(false); 

    panel.add(scroll); 
} 

등을 프레임에 추가 ..

public class Frame { 
    SomePanel panel; 
public Frame(){ 
     */* 
     * Construct frame etc 
     */* 
     frame.add(panel = new SomePanel()); 
     } 
} 

답변

2

그것은 왜냐하면 두 번째 경우에 , SomePanel은 Component에서 확장 된 클래스가 아니므로 JFrame의 contentPane과 같은 컨테이너에는 추가 할 수 없습니다.

frame.add(new SomePanel().getPanel()); 
+0

우수, 즉 완벽한 sense..thanks한다 :

public JComponent getPanel() { return panel; } 

하고 JFrame의에 추가 :이 문제를 해결하려면, 클래스를 다른 클래스가 포함 된 JPanel을 추출 할 수있는 방법을 제공 댓글! –

관련 문제