2014-10-12 5 views
3

저는 Java에 익숙하지 않기 때문에 어떤 문제가 있는지 잘 모릅니다. 여기에있는 코드는 실행될 때 한 번 창을 열어야하는 코드입니다. 그러나 ColoredWordsExperiment 클래스를 ButtonHandler 클래스로 확장 할 때마다 창은 무한히 빠르게 열리고 거의 언제든지 컴퓨터가 충돌합니다. 확장 기능을 생략하면 잘 동작하지만, ButtonHandler 클래스의 ColoredWordsExperiment 클래스의 객체를 사용할 수 없게됩니다. 코드 아래에서 코드를 찾을 수 있습니다 (그렇지 않은 경우, d가 너무 길어진다).클래스를 확장 할 때 오류가 발생했습니다.

public class ColoredWordsExperiment { 
    JFrame frame; 
    ButtonHandler buttonHandler; 

ColoredWordsExperiment(){ 
    frame = new JFrame("Colored Words Experiment"); 
    frame.setSize(1200, 150); 
    frame.setVisible(true); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    button1 = new JButton("Matching"); 

    label1 = new JLabel("test"); 
    label1.setPreferredSize(new Dimension(90, 40)); 

    JPanel labelContainer = new JPanel(); 
    labelContainer.add(label1); 

    JPanel buttonContainer = new JPanel(); 
    buttonContainer.add(button1); 

    frame.add(buttonContainer, BorderLayout.SOUTH); 
    frame.add(labelContainer, BorderLayout.NORTH); 

    buttonHandler = new ButtonHandler(); 
    button1.addActionListener(buttonHandler); 
} 

public static void main(String[] arg) { 
    new ColoredWordsExperiment(); 
} 

} 

-, 당신이 그 ButtonHandlers 중 하나 만드는 부모 클래스의 생성자에서

public class ButtonHandler extends ColoredWordsExperiment implements ActionListener { 
@Override 
public void actionPerformed(ActionEvent e){ 
    if (e.getActionCommand().equals("Matching")) { 
     System.out.println("Matching"); 
     label1.setText("Text changed"); 
    } 
} 
} 

답변

2

이 경우 ColoredWordsExperiment을 확장 할 이유가 없습니다. 단순히 ActionListener을 구현해야합니다.

본질적으로 하나의 추가 방법으로 ColoredWordsExperiment의 내부를 초기화합니다. 이렇게하면 생성자가 다시 호출되어 GUI 창이 다시 생성됩니다.
자세한 내용은 Inheritance을 참조하십시오.

ColoredWordsExperiment의 입력란을 ActionListener 구현에서 변경하려면 작성 중에 참조를 전달해야합니다.

public class ButtonHandler implements ActionListener { 
    ColoredWordsExperiment coloredWords; 
    public ButtonHandler(ColoredWordsExperiment coloredWords) { 
     this.coloredWords = coloredWords; 
    } 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     if (e.getActionCommand().equals("Matching")) { 
      System.out.println("Matching"); 
      coloredWords.label1.setText("Text changed"); 
     } 
    } 
} 
이 경우

은 또한 익명의 내부 클래스를 생성하는 옵션이 있습니다. 이 기술을 사용하면 ButtonHandler 클래스를 완전히 제거 할 수 있습니다.
내부 ColoredWordsExperiment 대신

buttonHandler = new ButtonHandler(); 
button1.addActionListener(buttonHandler); 

의 당신은

button1.addActionListener(new ActionListener() { 
    if (e.getActionCommand().equals("Matching")) { 
     System.out.println("Matching"); 
     label1.setText("Text changed"); 
    } 
}); 

내가 무엇 투어 문제를 볼 수 있습니다 Anonymous Classes

+1

코드가 그와 같은 역할을하는 이유를 설명해야합니다. – Alvaro

+0

하지만 "일치하는"버튼을 클릭 할 때마다 label1 텍스트를 변경하고 싶습니다. ButtonHandler에서 ColoredWordsExperiment를 확장하지 않으면 어떻게됩니까? Label1.setText ("Text changed") 이후입니다. ColoredWordsExperiment를 확장하지 않으면 작동하지 않습니다. – Ken

+0

익명의 내부 클래스에 대한 설명과 함께 자세한 내용을 추가로 편집했습니다. 두 솔루션 모두이를 처리해야합니다. – Justin

1

는 느릅 나무, 다시, 다시 생성자 코드를 실행합니다. 이 클래스를 생성자에서 인스턴스화하면 안됩니다 (동일한 이름을 사용하려고 시도하는 경우 다른 클래스 이름을 사용하지 마십시오)

0

좋아 참조 사용할 수 있습니다. 이제 내가 왜 확장하고 싶은지 모르겠다. 나는 단지 당신의 질문에 대답하려고 노력하고있다. (b/c 액션 리스너를 메인 클래스로 확장 할 필요가 없다.) 클래스 메서드를 정의 할 때 public을 두지 않고 main 메서드를 실행하면 혼동을 일으켜 무한한 프레임을 만들 수 있습니다. 이로 변경해야합니다

public class ColoredWordsExperiment { 
    JFrame frame; 
    ButtonHandler buttonHandler; 

    public ColoredWordsExperiment(){//add the public! 
    frame = new JFrame("Colored Words Experiment"); 
    frame.setSize(1200, 150); 
    frame.setVisible(true); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    button1 = new JButton("Matching"); 

    label1 = new JLabel("test"); 
    label1.setPreferredSize(new Dimension(90, 40)); 

    JPanel labelContainer = new JPanel(); 
    labelContainer.add(label1); 

    JPanel buttonContainer = new JPanel(); 
    buttonContainer.add(button1); 

    frame.add(buttonContainer, BorderLayout.SOUTH); 
    frame.add(labelContainer, BorderLayout.NORTH); 

    buttonHandler = new ButtonHandler(); 
    button1.addActionListener(buttonHandler); 
    } 

    public static void main(String[] arg) { 
     new ColoredWordsExperiment(); 
    } 

} 

또한, 그것은 자신의 메인 클래스에 ButtonHandler 클래스로 buttonHandler 변수를 정의하지만, 다음 ButtonHandler 클래스는 자신의 메인 클래스를 확장해야하는 좋은 아이디어가 아니다. 루프가 생길 수 있습니다. 두 번째 클래스를 확장하거나 buttonHandler 변수를 다른 방식으로 정의해야합니다.

0

개체 사이의 차이점을 읽고 이해해야하는 것처럼 들립니다.난 당신이 원래 간단한 예와 코드에 대해 생각했다 방식에 문제를 설명하기 위해 원하는 당신을 도와하려면 :

예상대로
class A { 
    int x; 
    B b = new B(); 
} 

class B extends A { 
} 

class Main { 
    public static void main(String args[]) { 
     A a = new A(); 
     a.x = 42; 
     a.b.x = 53; 

     System.out.println(a.x); 
     System.out.println(a.b.x); 
    } 
} 

, 객체 main()ax라는 이름의 필드가 우리가 설정할 수 있습니다 그것은 42 그러나 a의 대상 b 내부 객체 a의 내부 필드 x-전혀 관계가없는 것입니다 x 이름 자신의 필드가 있습니다.

당신이 객체의 개념에 대해 머리를 맞출 수 있다면 좋은 자바 프로그래머가되는 길에 잘 들어갈 것입니다.

관련 문제