开发者

Is it possible to draw an image or text on a JFrame?

开发者 https://www.devze.com 2023-02-21 18:14 出处:网络
Is it possible to draw on a JFrame without adding a JPanel to it? i override paintComponents() but it didn\'t show anything.

Is it possible to draw on a JFrame without adding a JPanel to it?

i override paintComponents() but it didn't show anything.

 @Over开发者_如何转开发ride
public void paintComponents(Graphics g) {
    super.paintComponents(g);
    g.drawString("for test", 10, 10);
}


Just in case anybody still insists of painting on the top-level Window directly (which is not recommended), here's how (because the code snippet linked to in the other answer is simply wrong)

    JFrame frame = new JFrame("funny ...") {

       @Override
       public void paint(Graphics g) {
           super.paint(g);
           g.drawString("for test", 150, 150);
       }

    };
    frame.getRootPane().setOpaque(false);
    ((JComponent) frame.getContentPane()).setOpaque(false);

Obviously, to make it shine-through all the way up, everything above (in Z-order) has to be not-opaque.

Cheers Jeanette


Yes, it is. You'll want to work with the one of the panes in the JFrame such as the content pane or the glass pane, which you can access via getContentPane, etc.

For example the content pane is a Container, with a variety of add methods. To that you can add any Component - doesn't have to be a JPanel specifically. More at Using Top Level Containers.

Usually, though, drawing is done via overriding paint (for AWT) or paintComponent (for Swing). This means you need some sort of Component or JComponent that you put in your frame. More at the 2D Graphics tutorial. Why do you not want to change that?

You can also override JFrame and its content pane and have a content pane with an override paintComponent method.

I question, however, the necessity and wisdom of directly drawing on a JFrame.


It seems to be possible. Check this previous SO post to see how it can be done.


JFrames have a GlassPane on top of them, which can be used for graphics. Here you have a simple example that shows how to use it.

0

精彩评论

暂无评论...
验证码 换一张
取 消