2013-08-18 3 views
0

저는 Java에 익숙하지 않아 방금 GUI 테스트로이 멍청한 프로그램을 작성하기 시작했습니다. 그것이 해야하는 것은 12 개의 버튼을 가지고 있고, 모두 흰색으로 설정하고, 3 개의 무작위 버튼을 검정색으로 만들고, 모든 버튼을 다시 흰색으로 설정하고, 1 초를 기다린 다음 반복합니다. 문제는 반복 할 수없는 것입니다. 랜덤 버튼을 검정색으로 만드는 코드 섹션 주위에 for 나 for 루프를 넣으려고 할 때마다 단순히 실행되지 않습니다. 오류가 발생하지 않으며 프로세스 자체가 실행되지만 창이 표시되지 않습니다. 이 클래스의 코드입니다 (가져 오기 문을 제외한) :GUI에서 루프 문제 (java)

public class testingness extends JFrame { 

JButton one, two, three, four, five, six, seven, eight, nine, ten, eleven, 
     twelve; 
JPanel panel; 

testingness(String title) { 

    super(title); 
    this.init(); 
    this.setSize(800, 800); 
    this.setLocationRelativeTo(null); 
    this.setVisible(true); 
} 

void init() { 
    panel = new JPanel(); 
    panel.setLayout(new GridLayout(3, 4)); 
    one = new JButton(); 
    one.setBackground(Color.white); 
    two = new JButton(); 
    two.setBackground(Color.white); 
    three = new JButton(); 
    three.setBackground(Color.white); 
    four = new JButton(); 
    four.setBackground(Color.white); 
    five = new JButton(); 
    five.setBackground(Color.white); 
    six = new JButton(); 
    six.setBackground(Color.white); 
    seven = new JButton(); 
    seven.setBackground(Color.white); 
    eight = new JButton(); 
    eight.setBackground(Color.white); 
    nine = new JButton(); 
    nine.setBackground(Color.white); 
    ten = new JButton(); 
    ten.setBackground(Color.white); 
    eleven = new JButton(); 
    eleven.setBackground(Color.white); 
    twelve = new JButton(); 
    twelve.setBackground(Color.white); 

    panel.add(one); 
    panel.add(two); 
    panel.add(three); 
    panel.add(four); 
    panel.add(five); 
    panel.add(six); 
    panel.add(seven); 
    panel.add(eight); 
    panel.add(nine); 
    panel.add(ten); 
    panel.add(eleven); 
    panel.add(twelve); 

    this.add(panel); 
    while (true) { 
     randomness(); 
     try { 
      Thread.sleep(1000); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 

public void randomness() { 

    for (int timesdone = 0; timesdone < 4; timesdone++) { 
     panel.update(panel.getGraphics()); 
     Random r = new Random(); 
     int rand = r.nextInt(12); 

     if (rand == 0) { 
      one.setBackground(Color.black); 
     } else if (rand == 1) { 
      two.setBackground(Color.black); 
     } else if (rand == 2) { 
      three.setBackground(Color.black); 
     } else if (rand == 3) { 
      four.setBackground(Color.black); 
     } else if (rand == 4) { 
      five.setBackground(Color.black); 
     } else if (rand == 5) { 
      six.setBackground(Color.black); 
     } else if (rand == 6) { 
      seven.setBackground(Color.black); 
     } else if (rand == 7) { 
      eight.setBackground(Color.black); 
     } else if (rand == 8) { 
      nine.setBackground(Color.black); 
     } else if (rand == 9) { 
      ten.setBackground(Color.black); 
     } else if (rand == 10) { 
      eleven.setBackground(Color.black); 
     } else if (rand == 11) { 
      twelve.setBackground(Color.black); 
     } 
     one.setBackground(Color.white); 
     two.setBackground(Color.white); 
     three.setBackground(Color.white); 
     four.setBackground(Color.white); 
     five.setBackground(Color.white); 
     six.setBackground(Color.white); 
     seven.setBackground(Color.white); 
     eight.setBackground(Color.white); 
     nine.setBackground(Color.white); 
     ten.setBackground(Color.white); 
     eleven.setBackground(Color.white); 
     twelve.setBackground(Color.white); 

    } 
    } 

} 

여기서 내가 뭘 잘못하고 있니?

+0

일부 중단 점 및 모니터에 넣어 너의 행동 프로그램. 그것은 시도를 호출하는 것입니다, 귀하의 모든 setbackground 호출을 호출하는 아마도 어쩌면 그것은 단지 새로 고침 디스플레이. 먼저 논리를 확인해 보겠습니다. – mwjohnson

+0

(http://stackoverflow.com/questions/18266087/change-jlabel-background-on-mouserelease-event/18293834#18293834) – MadProgrammer

+0

당신은 update' 또는 '페인트'를 호출해서는 안 [예]에서 살펴 본다보십시오 '디렉토리,이 panel.update (panel.getGraphics());는 매우 나쁨 – MadProgrammer

답변

2

Germann Arlington이 지적했듯이 GUI 스레드는 생성자가 결코 반환하지 않기 때문에 실행을 허용하지 않습니다. 그러나 GUI 스레드 (GUI 구성 요소의 속성을 변경해야하는)에서 정기적으로 수행되는 작업을 얻는 더 좋은 방법은 타이머 (http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html)를 사용하는 것입니다. 예 :

int delay = 1000; //milliseconds 
ActionListener taskPerformer = new ActionListener() { 
    public void actionPerformed(ActionEvent evt) { 
     randomness(); 
    } 
}; 
new Timer(delay, taskPerformer).start(); 
+1

이것은 더 좋은 대답이지만, OP는 여전히'randomness' 메소드에 문제가있을 것입니다 ... – MadProgrammer

2

randomness() 함수의 끝에서 모든 버튼을 흰색으로 설정합니다. 그 뒤에서 대신에 if-elses보다 위에 올려야합니다.

0

주된 문제는 코드가 실행된다는 것입니다. 그러나 루프를 끝내지 않으므로 구성 요소를 페인트하지 못할 수 있습니다. 루프 내에서 메서드의 끝에서 repaint() 메서드를 호출 해보십시오.

다른 점 : 여러 개의 버튼이있는 경우에는 컨테이너에 해당 버튼 만 추가하고이 컨테이너 내용 위로 반복하는 것이 더 좋습니다 (프로그래밍 방식).

4

스윙은 단일 스레드 환경입니다. UI에 대한 모든 상호 작용 및 수정은 Event Dispatching Thread의 컨텍스트 내에서 수행되어야합니다. 다른 것들 사이에, 프로세스가 요청 및 수신 이벤트

동부 서머 타임이 이벤트를 처리하고 화면을 갱신하는 것을 방지합니다 차단 조치 또는 작업을 다시 칠을위한

동부 서머 타임은 책임이있다. 당신이하고있는 코드에서

...

while (true) { 
    randomness(); 
    try { 
     Thread.sleep(1000); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

이 가능성이 그 어느 화면을 갱신에서 그것을 방지 EDT를 차단하고 있습니다. 당신이이 일을 동등하게

...

for (int timesdone = 0; timesdone < 4; timesdone++) { 
    /*...*/ 
} 

는 또한

는이 panel.update(panel.getGraphics()); 매우이다 동등하게, 지금까지 화면을 갱신에서 그것을 방지 EDT를 차단하는 것입니다 ... 나쁜 생각. Swing에서는 페인트 프로세스를 제어하지 않습니다. 최대 값은 RepaintManager입니다. 업데이트/다시 칠하기 요청을 할 수는 있지만 언제, 무엇을 결정할지는 최대 RepaintManager입니다. 이러한 요청은 EDT에 게시되며 차단 된 경우 아무 것도 수행하지 않습니다.

getGraphicsnull을 반환 할 수 있습니다.

문제를 해결하기 위해, 당신은 떨어져

당신은 사용할 수 ... 준비, 그에 따라 그 상태를 변경하는 UI를 말할 필요가 백그라운드 프로세스의 일종에 "대기"시간을로드해야합니다 a Thread,하지만 그건 당신이 모든 전화를 EDT로 다시 동기화하는 책임을 져야한다는 것을 의미합니다. 이것은 번거롭고 오버 헤드에 대한 이득이 거의 없습니다.

당신은 SwingWorker 사용할 수 있지만 그것은 정말 당신이 손에 가지고 작업에 적합하지있어

이기 때문에 더 나은 솔루션, 지정된 지연 후에 반복적으로 actionPerformed 이벤트를 트리거하는 javax.swing.Timer을 사용하는 것입니다 EDT의 맥락에서 실행된다.

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.Random; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.Timer; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class Flashy01 { 

    public static void main(String[] args) { 
     new Flashy01(); 
    } 

    public Flashy01() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new FlashPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class FlashPane extends JPanel { 

     private final BigButton one, two, three, four, five, six, seven, eight, nine, ten, eleven, 
       twelve; 
     private final JPanel panel; 
     private final Random random; 
     private int timesDone; 

     public FlashPane() { 
      panel = new JPanel(); 
      panel.setLayout(new GridLayout(3, 4)); 
      one = new BigButton(); 
      one.setBackground(Color.white); 
      two = new BigButton(); 
      two.setBackground(Color.white); 
      three = new BigButton(); 
      three.setBackground(Color.white); 
      four = new BigButton(); 
      four.setBackground(Color.white); 
      five = new BigButton(); 
      five.setBackground(Color.white); 
      six = new BigButton(); 
      six.setBackground(Color.white); 
      seven = new BigButton(); 
      seven.setBackground(Color.white); 
      eight = new BigButton(); 
      eight.setBackground(Color.white); 
      nine = new BigButton(); 
      nine.setBackground(Color.white); 
      ten = new BigButton(); 
      ten.setBackground(Color.white); 
      eleven = new BigButton(); 
      eleven.setBackground(Color.white); 
      twelve = new BigButton(); 
      twelve.setBackground(Color.white); 

      panel.add(one); 
      panel.add(two); 
      panel.add(three); 
      panel.add(four); 
      panel.add(five); 
      panel.add(six); 
      panel.add(seven); 
      panel.add(eight); 
      panel.add(nine); 
      panel.add(ten); 
      panel.add(eleven); 
      panel.add(twelve); 

      this.add(panel); 
      random = new Random(); 

      Timer timer = new Timer(1000, new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        randomness(); 
       } 
      }); 
      timer.start(); 
     } 

     public void randomness() { 

      int rand = random.nextInt(12); 
      timesDone++; 

      if (timesDone % 5 != 0) { 

       if (rand == 0) { 
        one.setBackground(Color.black); 
       } else if (rand == 1) { 
        two.setBackground(Color.black); 
       } else if (rand == 2) { 
        three.setBackground(Color.black); 
       } else if (rand == 3) { 
        four.setBackground(Color.black); 
       } else if (rand == 4) { 
        five.setBackground(Color.black); 
       } else if (rand == 5) { 
        six.setBackground(Color.black); 
       } else if (rand == 6) { 
        seven.setBackground(Color.black); 
       } else if (rand == 7) { 
        eight.setBackground(Color.black); 
       } else if (rand == 8) { 
        nine.setBackground(Color.black); 
       } else if (rand == 9) { 
        ten.setBackground(Color.black); 
       } else if (rand == 10) { 
        eleven.setBackground(Color.black); 
       } else if (rand == 11) { 
        twelve.setBackground(Color.black); 
       } 

      } else { 

       one.setBackground(Color.white); 
       two.setBackground(Color.white); 
       three.setBackground(Color.white); 
       four.setBackground(Color.white); 
       five.setBackground(Color.white); 
       six.setBackground(Color.white); 
       seven.setBackground(Color.white); 
       eight.setBackground(Color.white); 
       nine.setBackground(Color.white); 
       ten.setBackground(Color.white); 
       eleven.setBackground(Color.white); 
       twelve.setBackground(Color.white); 
      } 
     } 
    } 

    public class BigButton extends JButton { 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(20, 20); 
     } 

    } 
} 

한 번 봐 ...

...

+0

와우, 나는하지 않았다. 스윙에 대해이 모든 것을 알지 못합니다. 공유해 주셔서 감사합니다. 언급 한 주제를 확실히 살펴 보겠습니다. – EyedJellyfish