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);
}
}
好的,謝謝我對actionlisteners不太擅長,我希望只是用鼠標點擊 – Robert 2012-02-14 01:26:24
閱讀單選按鈕上的教程,因爲這可能會在那裏解釋。 – 2012-02-14 01:27:51
好的,謝謝你的幫助 – Robert 2012-02-14 01:28:56