在没有组件的情况下设置JPanel的大小 [英] Set size of JPanel, when there are no components in it
问题描述
我有一个自定义的JPanel.其中唯一的东西是使用Graphics
对象的drawRect
方法绘制的矩形. JPanel始终具有特定的正方形大小,拒绝将其放大或缩小.尝试覆盖getPreferredSize()
方法,没有用.
I have a custom JPanel. The only thing that is in it, is a drawing of a rectangle, using the drawRect
method of the Graphics
object. The JPanel is always in a very specific square size, refuses to get any bigger or smaller. Tried overriding the getPreferredSize()
method, didn't work.
尝试为此自定义JPanel设置不同的布局管理器,并且还尝试了承载此JPanel的JPanel的每个布局管理器.不过,自定义JPanel的大小保持不变.
Tried setting different layout managers for this custom JPanel, and also tried every layout manager for the JPanel that hosts this JPanel. Still, the size of the custom JPanel stays the same.
正如我所说,自定义的JPanel中没有任何组件,只有一个矩形图.
As I said, the custom JPanel has no components in it, only a drawing of a rectangle.
有什么想法吗?
推荐答案
不了解您要实现的目标:
Without knowing more about what you're trying to achieve:
-
对于您的包含面板,您需要知道哪些布局管理器尊重首选尺寸,哪些布局管理者不尊重
As far as your containing panel, you need to know which layout managers respect preferred sizes and which ones don't
Grid Flow Border Box GridBag
Respect PreferredSize NO YES NO YES YES
话虽如此,如果您将带"NOs" 之一的彩绘JPanel
包装在JPanel
中,则彩绘JPanel
应该随着尺寸的调整而伸展框架.
That being said, if you wrap the painted JPanel
in a JPanel
with one of the "NOs", the painted JPanel
shoud stretch with the resizing of the frame.
此外,如果要使绘制的矩形及其JPanel
一起拉伸,则需要记住使用JPanel
的getWidth()
和getHeight()
绘制矩形,并且不要使用硬编码值.
Also if you want the drawn rectangle to stretch along with its JPanel
, then you need to remember to draw the rectangle with getWidth()
and getHeight()
of the JPanel
and not use hard coded values.
在此示例使用BorderLayout
作为包含面板的布局,并在执行绘画时使用getWidth()
和getHeight()
.
Here is an example using BorderLayout
as the containing panel's layout, and making use of getWidth()
and getHeight()
when performing the painting.
import java.awt.*;
import javax.swing.*;
public class StretchRect {
public StretchRect() {
JPanel panel = new JPanel(new BorderLayout());
panel.add(new RectanglePanel());
JFrame frame = new JFrame();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class RectanglePanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect( (int)(getWidth() * 0.1), (int)(getHeight() * 0.1),
(int)(getWidth() * 0.8), (int)(getHeight() * 0.8) );
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new StretchRect();
}
});
}
}
这篇关于在没有组件的情况下设置JPanel的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!