한 클래스에서 ActionListener를 사용하여 다른 클래스에서 타이머를 시작합니다.

StackOverflow https://stackoverflow.com/questions/1418007

문제

다른 클래스 (GUI)의 인스턴스를 만드는 클래스 (시뮬레이션)가 있습니다. 클래스 GUI 내부에는 ActionListener가 첨부 된 버튼 (시작)이 있습니다.

시뮬레이션에서 타이머를 시작하려면이 ActionListener가 필요하지만 어떻게 해야하는지 알 수 없습니다.

수업 시뮬레이션 코드 :

public class Simulation{

private static JFrame frame;
private static GUI control;
public static Integer xcontrol = 100, ycontrol = 100;

public Timer timer;
public int steps;

public static void main(String[] args) {
    Simulation sim = new Simulation ();

}

public Simulation() {

frame = new JFrame("Action Listener Test");
frame.setLayout(new BorderLayout(1,0));

control = new GUI (xcontrol, ycontrol);
frame.getContentPane().add(control , BorderLayout.CENTER);

frame.setResizable(false);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}


public void StartTimer() {
    timer.start();
    System.out.println("It worked!");   
}

클래스 GUI의 코드 :

        panel1.add(button1a);

            button1a.addActionListener(new ActionListener() {
                public void actionPerformed (ActionEvent event) {
                    Simulation.StartTimer();
                    }
                } );

Eclipse는 "Simulation.timer.start ();" :

유형 시뮬레이션에서 비 정적 메소드 StartTimer ()를 정적으로 참조 할 수 없습니다.

그러나 메소드 startTimer ()는 타이머를 깨뜨리는 것처럼 보이므로 정적이 될 수 없습니다 ...

모든 도움은 대단히 감사 할 것입니다.

도움이 되었습니까?

해결책

통과하다 this 에 대한 논쟁으로 GUI 건설자.

일반적으로 그러한 주기적 참조를 피하는 것이 가장 좋습니다. 둘 다 GUI 그리고 Simulator 서로에 의존하게됩니다. 솔루션의 본질은 GUI를 흥미로운 영역 별 동작과 분리하는 것입니다.

(BTW : 상수 이외의 다른 것에 대한 정적 변수를 사용하지 않습니다. 또한 비 개인적인 인스턴스 변수를 피하십시오. JFrame!)

멀티 스레딩을 방지하기 위해 추가해야 할 끔찍한 보일러 플레이트가 있습니다.

public static void main(final String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
                Simulation sim = new Simulation();
    }});
}

다른 팁

내가 할 일은 GUI 클래스가 getButton () 메소드를 통해 버튼을 노출 시키게하는 것입니다. 그런 다음 GUI 객체를 작성한 후 시뮬레이션 클래스는 버튼 (예 : 컨트롤)에 자체 액션 리스트너를 추가 할 수 있습니다. )... 등.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top