2
강사와 함께이 서문을 시작해야 클래스에서 IDE를 사용할 수 없기 때문에 텍스트 패드에서이 작업을 수행하고 있습니다. raido 버튼을 클릭하고 "신호등"색상을 변경하고 싶습니다. 라디오 버튼과 상호 작용하기 위해 getSource()를 어떻게 사용합니까?JRadioButton에서 getSource()를 어떻게 사용합니까?
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Lab4Frame extends JFrame {
Lab4Frame(){
setTitle("Lab 4 - Application #1");
Lab4Panel p = new Lab4Panel();
Lab4RadioButtonPanel p2 = new Lab4RadioButtonPanel();
setLayout(new GridLayout(2,1));
add(p);
add(p2);
}
public static void main(String[] args){
Lab4Frame frame = new Lab4Frame();
frame.setTitle("Lab4 Application # 1");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setVisible(true);
}
}
class Lab4RadioButtonPanel extends JPanel implements MouseListener {
public Lab4RadioButtonPanel() {
this.setLayout(new FlowLayout());
JRadioButton jrbRed = new JRadioButton("Red", true);
JRadioButton jrbYellow = new JRadioButton("Yellow");
JRadioButton jrbGreen = new JRadioButton("Green");
this.setBorder(BorderFactory.createLineBorder(Color.black));
ButtonGroup group = new ButtonGroup();
group.add(jrbRed);
group.add(jrbYellow);
group.add(jrbGreen);
this.add(jrbRed);
this.add(jrbYellow);
this.add(jrbGreen);
jrbRed.setMnemonic('E');
jrbGreen.setMnemonic('G');
jrbYellow.setMnemonic('Y');
}
public void mouseClicked(MouseEvent e)
{
if (e.getSource() == jrbRed){
}
else if (e.getSource() == jrbYellow){
}
else if (e.getSource() == jrbGreen){
}
}
public void mouseExited(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
}
class Lab4Panel extends JPanel{
public Lab4Panel(){
}
int height, width;
int radius = 5;
int x = -1;
int y = -1;
protected void paintComponent(Graphics g){
if (x<0 || y<0) {
x = getWidth()/2 - radius;
y = getHeight()/2 - radius;
}
super.paintComponent(g);
g.drawRect(x - 10,y - 90, 40, 120);
//g.drawOval(x,y - 80, 4 * radius, 4 * radius);
//g.drawOval(x,y - 40, 4 * radius, 4 * radius);
//g.drawOval(x,y, 4 * radius, 4 * radius);
g.drawRect(x - 5,y - 90, 40, 120);
g.setColor(Color.RED);
g.fillOval(x,y - 80, 4 * radius, 4 * radius);
g.setColor(Color.YELLOW);
g.fillOval(x,y - 40, 4 * radius, 4 * radius);
g.setColor(Color.GREEN);
g.fillOval(x,y, 4 * radius, 4 * radius);
}
}
좋아, 고맙습니다. 나는 단지 mouseClicked를 사용하고 싶었던 actionlisteners가 좋지 않습니다. – Robert
라디오 버튼에 대한 자습서를 읽으므로 여기에 설명되어 있습니다. –
도와 주셔서 감사합니다. – Robert