2014-04-14 2 views
1

내 프로그램에 세 개의 버튼이 있어야합니다 (마지막 버튼은 종료 버튼이며 이미 작동 중입니다). 다른 두 개는 파란색과 빨간색 사이의 배경색 인 JPanel의 색을 변경해야합니다.JButton을 사용하여 JPanel의 배경색을 변경하려면 어떻게해야합니까?

AtionListeners에 무엇이 들어가는지 알아야 버튼을 누르면 배경색이 변경됩니다.

이 지금까지 클래스입니다 : 당신은 문을 결정하는 경우, 당신은 단지 동일한 하나를 사용하여 추가 할 수 있습니다 각 버튼에 대한 리스너 클래스를 선언 할 필요는 없습니다

package myPackageNameGoesHere; 

import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JPanel; 

public class EventPanel extends JPanel { 
private static final long serialVersionUID = 123796234; 

private JButton blueButton; 
private JButton redButton; 
private JButton exitButton; 

public EventPanel() { 
    this.setPreferredSize(new Dimension(200, 300)); 

    this.blueButton = new JButton("Blue"); 
    this.add(this.blueButton); 

    this.redButton = new JButton("Red"); 
    this.add(this.redButton); 

    this.exitButton = new JButton("Exit"); 
    this.exitButton.addActionListener(new ExitListener()); 
    this.add(this.exitButton); 
} 

private class BlueListener implements ActionListener { 
    @Override 
    public void actionPerformed(ActionEvent blue) { 
     // What goes here????? 

    } 
} 

private class RedListener implements ActionListener { 
    @Override 
    public void actionPerformed(ActionEvent red) { 
     // What goes here???? 

    } 
} 
private class ExitListener implements ActionListener { 
    @Override 
    public void actionPerformed(ActionEvent exit) { 
     System.exit(0); 
    } 
} 
} 
+0

이 http://stackoverflow.com/questions/4219919/how-to-change-the- 시도 background-color-on-a-java-panel – Dan

답변

2

하는 액션 버튼에서 와라.

if (e.getSource() == blueButton) {// e is the ActionEvent 
    blueButton.getParent().setBackground(Color.BLUE); 
} else if(e.getSource() == redButton) { 
    redButton.getParent().setBackground(Color.RED); 
} 
+0

고마워요! 위대한 작품! – user3241721

2

당신은 버튼의 부모 구성 요소의 배경 색상을 설정할 수 있습니다

Component component = (Component) event.getSource(); 
component.getParent().setBackground(Color.BLUE); 
관련 문제