0
我想要實現的是兩個按鈕,使用戶可以選擇顏色(黑色或紅色),然後根據顏色繪製紅色或黑色形狀,例如,畫布上的矩形。 我有一個與按鈕連接的MouseListeners有關設置Canvas類中圖形顏色的問題。我應該在哪裏定義顏色?Java - 選擇在畫布上畫什麼
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類中的複選框的狀態是否可見? – whatfor