Drawing Canvas on JFrame(在 JFrame 上绘制画布)
问题描述
我正在尝试用 Canvas 绘制简单的形状,在这个类中我已经设置了绘画
在这个窗口中
它可以工作,但 JFrame 不适应 Canvas.我必须手动调整窗口大小才能看到对象.如何打包它以便 JFrame 自动包含 Canvas?
这真的很奇怪.虽然 frame.pack() 确实是必不可少的,但这还不够.我所做的是更改 start 方法并将其变成构造函数,如下所示:
然后,在另一个类中,Eclipse 抱怨直接调用构造函数(例如 ga.Game),所以我按照它的提示更改为:
这样我实现了我的想法,但我真的不知道为什么我不能调用构造函数.
我不知道你想做什么,但你不应该调用 paint
尤其是不通过它 null
.
首先查看
I'm trying to draw simple shapes with Canvas, in this class I've set the painting
And in this the Window
It works, but the JFrame is not adapting to the Canvas. I have to manually resize the window to see the objects. How can I pack it so that JFrame automatically encompasses the Canvas?
EDIT: That's really weird. While frame.pack() is indeed essential, it's not enough. What I did was change the start method and turn it into a constructor, like that:
then, from the other class, Eclipse complained about calling the constructor directly(E.G. ga.Game), so I followed it's tip and changed to:
This way I achieve what I have in mind but I really don't know why I can't call the constructor.
I don't know what it is you're trying to do, but you should NEVER be calling paint
and especially not pass it null
.
Start by taking a look at Performing Custom Painting and Painting in AWT and Swing for details about how painting works.
In order to get the window to size to you component, you need to provide it some important information.
While Window#pack
is the method you are looking for, it will not help you unless you provide appropriate sizing hints.
In this case, you need to override the getPreferredSize
method of you component and provide an appropriate size value. Window#pack
will use this value to determine what size it needs to be in order to accommodate it.
The paint chain is very important and you should avoid breaking it at all coasts. Make sure you always call super.paintXxx
or be prepared for some serious weirdness
Also may want to have a read of Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
这篇关于在 JFrame 上绘制画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!