첫 번째 버튼을 누를 때마다 사각형이 계속해서 다시 그려지고 두 번째 버튼을 누르면 색상이 변경되는 2 개의 버튼이있는 프로그램을 작성하려고합니다. 그러나 그것은 한 번만 다시 칠합니다 :( 누구나 도울 수 있다면 감사하겠습니다.
class Squre {
JFrame frame;
JButton button1;
JButton button2;
MyPanel panel;
public static void main(String[] args){
Squre s= new Squre ();
s.go();
}
public void go(){
frame = new JFrame();
panel= new MyPanel();
button1= new JButton();
button2= new JButton();
button1.setText("START");
//button1.setSize(30, 20);
frame.setVisible(true);
frame.setSize(700,700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER ,panel);// add panel
frame .getContentPane().add(BorderLayout.WEST, button1);// add the west button
frame .getContentPane().add(BorderLayout.EAST, button2);//ADD THE EAST BUTTON
button1.addActionListener(new StrListener());
button2.setText("EXPLOSION");
button2.addActionListener(new ExpListener());
}
private class StrListener implements ActionListener{
public void actionPerformed(ActionEvent e){
do{
frame.repaint();
}
while(e.equals(button2)==true);
}
}
private class ExpListener implements ActionListener{
// @Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}class MyPanel extends JPanel{
public void paintComponent(Graphics g){
g.fillRect(0,0,this.getWidth(),this.getHeight());
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color rn=new Color(red, green, blue);
g.setColor(rn);
g.fillRect(250, 250, 50, 50);
}
}}
e.equals(button1) // event not equal to a button
e.equals(button1)
.but event
과 같지 않기 때문에 결코 참이 되지 않습니다. button
하지만 repaint
do while 루프이기 때문에 한 번 실행됩니다.
당신은 사용해야합니다
e.getSource().equals(button1);
클릭 한 버튼의 유무를 확인합니다 button1
.
하지만 사용하더라도 e.getSource().equals(button1)
예상대로 색상이 변경되는 것을 볼 수 없습니다. EDT 내에서이 시간이 많이 걸리는 while 루프를 실행 하면 EDT
스레드 를 차단 하므로 색상이 변경되지 않지만을 넣으면 sout
루프가 계속 실행되는 것을 볼 수 있습니다. 이를 위해 스윙 타이머 를 사용할 수 있습니다 . 스윙 타이머는 EDT를 차단하지 않습니다.
스윙 타이머 사용 ....
swing timer
// 가져와야합니다.import javax.swing.Timer;
private class StrListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(button1)) {
Timer t = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
frame.repaint();
}
});
t.start();
}
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다