[英]Is it possible to draw an image or text on a JFrame?
Is it possible to draw on a JFrame
without adding a JPanel
to it? 是否可以在不添加JPanel
情况下绘制JFrame
?
i override paintComponents()
but it didn't show anything. 我重写paintComponents()
但什么也没显示。
@Override
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) 以防万一有人仍然坚持直接在顶层Window上绘画( 不建议这样做),这是怎么做的(因为在另一个答案中链接的代码段完全是错误的)
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. 显然,要使它一直发光,上面的所有内容(按Z顺序)必须不透明。
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. 您将需要使用JFrame中的一个窗格,例如内容窗格或玻璃窗格 ,您可以通过getContentPane等访问这些窗格 。
For example the content pane is a Container , with a variety of add methods. 例如,内容窗格是Container ,具有多种添加方法。 To that you can add any Component - doesn't have to be a JPanel specifically. 为此,您可以添加任何组件 -不必专门是JPanel。 More at Using Top Level Containers . 更多有关使用顶级容器的信息 。
Usually, though, drawing is done via overriding paint (for AWT) or paintComponent (for Swing). 但是,通常,绘制是通过覆盖绘制(对于AWT)或paintComponent(对于Swing)完成的。 This means you need some sort of Component or JComponent that you put in your frame. 这意味着您需要在框架中放入某种Component或JComponent 。 More at the 2D Graphics tutorial. 有关2D图形教程的更多信息。 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. 您还可以覆盖JFrame及其内容窗格,并具有一个带有重写paintComponent方法的内容窗格。
I question, however, the necessity and wisdom of directly drawing on a JFrame. 但是,我质疑直接使用JFrame的必要性和智慧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.