Hi everyone!
I'm doing a program in java to draw in the screen. I already have the code to do that, but, what I'm trying to do is to have another JPanel on top of drawingPanel so that, when I click somewhere I've already painted something (this method isn't implemented yet, but I know how to do it), I can move this shape all over the screen without repainting the main drawingPanel every mouse move. The idea is to have a transparent panel in with I'll just draw when I want to move something.
I've seen I can use glassPane, but it doesn't work to me, because this panel will be part of a bigger application, so, I cant have a transparent pannel allover the screen.
Here I let my working code with just one JPanel:
public class ScrollPanel extends JPanel implements MouseListener{
private Dimension area; //indicates area taken up by graphics
private Vector<Rectangle> circles; //coordinates used to draw graphics
private JPanel drawingPanel;
private final Color colors[] = {
Color.red, Color.blue, Color.green, Color.orange,
Color.cyan, Color.magenta, Color.darkGray, Color.yellow};
private final int color_n = colors.length;
public ScrollPanel() {
super(new BorderLayout());
area = new Dimension(0, 0);
circles = new Vector<Rectangle>();
drawingPanel = new DrawingPane();
drawingPanel.addMouseListener(this);
JScrollPane scroller = new JScrollPane(drawingPanel);
add(scroller, BorderLayout.CENTER);
}
public class DrawingPane extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Rectangle rect;
for (int i = 0; i < circles.size(); i++) {
rect = circles.elementAt(i);
g.setColor(colors[(i % color_n)]);
g.fillOval(rect.x, rect.y, rect.width, rect.height);
}
}
}
public void mouseReleased(MouseEvent e) {
final int W = 100;
final int H = 100;
boolean changed = false;
if (SwingUtilities.isRightMouseButton(e)) {
circles.removeAllElements();
area.width = 0;
area.height = 0;
changed = true;
} else {
int x = e.getX() - W / 2;
int y = e.getY() - H / 2;
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
Rectangle rect = new Rectangle(x, y, W, H);
circles.addElement(rect);
drawingPanel.scrollRectToVisible(rect);
int this_width = (x + W + 2);
if (this_width > area.width) {
area.width = this_width;
changed = true;
}
int this_height = (y + H + 2);
if (this_height > area.height) {
area.height = this_height;
changed = true;
}
}
if (changed) {
drawingPanel.setPreferredSize(area);
drawingPanel.revalidate();
}
drawingPanel.repaint();
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
}
Can anyone help me?
Thanks!