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

♀尐吖头ヾ 提交于 2019-12-08 11:28:34

问题


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

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

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

回答1:


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.




回答2:


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




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/5500680/is-it-possible-to-draw-an-image-or-text-on-a-jframe

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