Hello java programmers,
I want to draw some squares on layers using Graphics2D, course.
Here is my source code with problems:
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Draw extends JPanel {
private static final long serialVersionUID = 1L;
private List<Cube> cubes = new ArrayList<Cube>();
public static void main(String[] args) throws Exception {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Draw");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Draw gp = new Draw();
f.add(gp, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
});
}
Draw() {
this.setPreferredSize(new Dimension(400, 300));
Cube c1 = new Cube(new Point(10, 20), Color.red);
cubes.add(c1);
Cube c2 = new Cube(new Point(20, 30), Color.blue);
cubes.add(c2);
Cube c3 = new Cube(new Point(30, 40), Color.magenta);
cubes.add(c3);
Cube c4 = new Cube(new Point(40, 50), Color.green);
cubes.add(c4);
repaint();
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(new Color(0x00f0f0f0));
g2d.fillRect(0, 0, getWidth(), getHeight());
for (Cube c : cubes) {
c.draw(g2d);
}
}
private static class Cube {
private Point p;
private Color color;
public Cube(Point p, Color color) {
this.p = p;
this.color = color;
}
public void draw(Graphics g) {
g.setColor(this.color);
g.fillRoundRect(p.x, p.y, 64, 64, 6, 6);
}
}
}
After I added the four squares:
Cube c1 = new Cube(new Point(10, 20), Color.red);
cubes.add(c1);
Cube c2 = new Cube(new Point(20, 30), Color.blue);
cubes.add(c2);
Cube c3 = new Cube(new Point(30, 40), Color.magenta);
cubes.add(c3);
Cube c4 = new Cube(new Point(40, 50), Color.green);
cubes.add(c4);
The four squares can be seen, depending on the order added.
But I want to move the blue cube above all clubs (on top) without changing the order of adding cubes.
Similar to:
Cube c1 = new Cube(new Point(10, 20), Color.red);
cubes.add(c1);
Cube c2 = new Cube(new Point(20, 30), Color.blue);
[B][U]c2.setLayer(1);[/U][/B]
cubes.add(c2);
Cube c3 = new Cube(new Point(30, 40), Color.magenta);
cubes.add(c3);
Cube c4 = new Cube(new Point(40, 50), Color.green);
cubes.add(c4);
How can I do this?
Can someone help me?
We thank you!