【发布时间】:2017-04-25 18:21:38
【问题描述】:
我想要实现的是两个按钮,使用户能够选择颜色(黑色或红色),然后根据颜色绘制红色或黑色形状,例如画布上的矩形。 我在将与按钮连接的 MouseListener 与设置 Canvas 类中的图形颜色相关联时遇到问题。我应该在哪里定义颜色?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Can extends Canvas{
int x,y;
ArrayList<Point> points = new ArrayList<Point>();
Can(){
super();
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent k){
x = k.getX();
y = k.getY();
points.add(new Point(x,y));
repaint();
}
});
}
public void paint(Graphics g){
int x2, y2;
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black); //here is only black
for(Point p:points)
{
x2=(int)p.getX();
y2=(int)p.getY();
g2.fillRect(x2, y2, 10, 5);
}
}
}
class Win extends JFrame{
Win(String name){
super(name);
setLayout(new GridLayout());
JPanel p1 = new JPanel(new FlowLayout());
p1.setBackground(Color.cyan);
CheckboxGroup cg = new CheckboxGroup();
Checkbox red = new Checkbox("red", cg, true);
Checkbox black = new Checkbox("black", cg, false);
p1.add(red);
p1.add(black);
add(p1);
Can k = new Can();
add(k);
red.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent me){
System.out.println("Mouse click on red");
}
});
black.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent me){
System.out.println("Mouse click on black");
}
});
setSize(600, 400);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class ItM {
public static void main(String[] args) {
Win o = new Win("that's the window");
o.setVisible(true);
}
}
【问题讨论】:
-
在
paint()检查复选框的状态。然后根据选择的颜色选择颜色。 -
好的,但是我应该如何检查呢?复选框的状态在 Canvas 类中是否可见?