java 画布与面板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10388668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:50:20  来源:igfitidea点击:

Canvas vs. Panel

javacanvasjpanel

提问by Anonymous181

If I want to display ellipses and rectangles on a screen, should I use a canvas or a JPanel?

如果我想在屏幕上显示椭圆和矩形,我应该使用画布还是 JPanel?

What is the difference? When do I use each?

有什么区别?我什么时候使用每个?

采纳答案by JB Nizet

In general, if you're using Swing, you should only use Swing components. Mixing Swing and AWT components in the same GUI leads to strange results. So I would use a JPanel, or a raw JComponent.

通常,如果您使用 Swing,则应该只使用 Swing 组件。在同一个 GUI 中混合 Swing 和 AWT 组件会导致奇怪的结果。所以我会使用 JPanel 或原始 JComponent。

回答by paulsm4

Canvasis an AWT object; JPanelis a lightweight Java Swing object. If you have a Java Swing GUI, I'd strongly recommend using JPanel.

Canvas是一个 AWT 对象;JPanel是一个轻量级的 Java Swing 对象。如果您有 Java Swing GUI,我强烈建议您使用JPanel.

Here's a good link on JPanel:

这是JPanel上的一个很好的链接:

In the simplest case, you use a JPanelexactly the same way as you would a Panel. Allocate it, drop components in it, then add the JPanelto some Container. However, JPanelalso acts as a replacement for Canvas(there is no JCanvas)...

在最简单的情况下,您使用 aJPanel的方式与使用Panel. 分配它,将组件放入其中,然后添加JPanel到 some Container。但是,JPanel也可以作为Canvas(没有JCanvas)...的替代品 。

回答by Paul Vargas

Or you can use a JLabelif you want display static images like icons.

或者,JLabel如果您想显示图标等静态图像,则可以使用 a 。

BufferedImage image=
  new BufferedImage(100, 50, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();

// draw
g2.draw(new Ellipse2D.Double(x, y, rectwidth,rectheight));
g2.fill (new Ellipse2D.Double(0, 0, 100, 50));

JLabel label = new JLabel(new ImageIcon( image ));

回答by DSOI__UNUNOCTIUM

That kind of depends on what you like, but, I would use JFrame, it directly creates a window, and you can draw onto it. Canvas has its advantages, it let's you write one less import, it also separates window stuff from canvas graphics stuff, but it has its the disadvantages of not having access to window. it depends on what you like and need.

这取决于你喜欢什么,但是,我会使用 JFrame,它直接创建一个窗口,你可以在它上面画画。Canvas 有它的优点,它让你少写一个导入,它还将窗口内容与画布图形内容分开,但它的缺点是无法访问窗口。这取决于你喜欢什么和需要什么。