Reputation: 353
what I want to achieve is two buttons that enable the user choose the color ( black or red ) and then, depends on the color, draw red or black shape, e.g. rectangle on canvas. I have a problem with relating MouseListeners connected with buttons to setting color of the graphics in Canvas class. Where should I define the color?
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);
}
}
Upvotes: 0
Views: 579
Reputation: 324147
First of all you are using the Swing
tag so your application should be using Swing components, not AWT components. Swing components start with "J", except for Canvas, where the Swing component is JPanel
. You should then be overriding the paintComponent(...)
method, not paint().
If you want to paint objects with different color then you have two options:
Paint directly to a BufferedImage. The then shape will be painted with the currently selected color
Paint from an ArrayList of object that contain information about the shape to be painted, including the size/location/color
For working examples of both approaches check out Custom Painting Approaches.
Upvotes: 3