Painting over the top of components in Swing?

浪子不回头ぞ 提交于 2019-12-01 17:45:59

This is what I'm already doing (on a much simpler level obviously), and Swing paints the rectangle underneath the components added to it.

This is one case where you should override the paint() method of the panel and not the paintComponent() method. Then the custom painting will be done AFTER all the child components have been painted.

Use a Layered Pane:

http://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html

This allows you to create overlapping components.

Use a glass pane to handle the drag painting, and possibly events as well:

http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html#glasspane

mKorbel

hot really sure what do you really needed and final effect, maybe is there two another ways painting to

1) GlassPane

2) Viewport

you can put that together, carrefully Insets to the visible Rectanle

Without seeing your actual code, it is difficult to say what you are doing wrong. However, I can still say what I would do:

Create a JPanel that represents the whole area where you want to draw, which — of course — contains every component.
Override that panel its paintComponents(Graphics) like this (EDITED, notice the s is now the last character from the method name):

@Override
public void paintComponents(Graphics g)
{ //                      ^
    super.paintComponents(g);

    // Draw your selection rectangle:
    g.setColor(Color.RED);
    g.drawRectangle(selectionRectangle); 
}

Okay, this is what I've decided to do in the end:
I'm not sure if this is the best way to do it, but it seems to work okay.
Note: Using MigLayout.

In the constructor of the JPanel lying underneath the colored blocks.

 ...
 this.add(new JPanel() {

     @Override
     public boolean isOpaque() {
        return false;
     }

     @Override
     public void paintComponent(Graphics g) {
        if (dragShape != null) {
           g.setColor(Colors.SECONDARY);
           g.setStroke(new BasicStroke(2));
           g.draw(dragShape);
        }
     }
  }, "pos 0 0, width 100%, height 100%", 0);
  ...

Custom painting on top of Swing components is facilitated by JLayeredPane. This article describes an abstract base class that facilitates overpainting specific areas (like selection rectangles or component bounds).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!