【发布时间】:2014-01-22 12:51:38
【问题描述】:
我目前的项目涉及将多个 JPanel 合二为一。我面临的问题是: ChildPanels 的内容会自动调整大小,而我并不想要这个。 我不不使用布局管理器,我只是更喜欢自己调整所有内容的大小。
有什么办法可以防止自动调整大小?
一些示例代码:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
JFrame f = new JFrame("TestFrame");
f.setVisible(false);
f.setLayout(null);
f.setLocation(100, 100);
f.setSize(350, 350);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ChildPanel cp1 = new ChildPanel(Color.red, 20, 20);
ChildPanel cp2 = new ChildPanel(Color.blue, 120, 120);
ParentPanel pp = new ParentPanel();
pp.add(cp1);
pp.add(cp2);
f.getContentPane().add(pp);
f.setVisible(true);
}
public static class ChildPanel extends JPanel {
private Color col;
public ChildPanel(Color col, int x, int y) {
super();
this.col = col;
setSize(50, 50);
setLocation(x, y);
}
@Override
public void paintComponent(Graphics g) {
g.setColor(col);
g.fillRect(0, 0, 50, 50);
}
}
public static class ParentPanel extends JPanel {
public ParentPanel() {
super();
setSize(200, 200);
setLocation(50, 50);
}
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.black);
int w = getWidth();
int h = getHeight();
g.fillRect(0, 0, w, h);
}
}
}
【问题讨论】:
-
布局管理器的存在是有原因的,如果你“更喜欢”手动做事,那么你将不得不一直解决这样的问题——更不用说如果你的代码最终会发生什么在一些不幸的 Mac 或 Linux PC 上。
-
我的代码不是为在 Linux 或 Mac 上工作而设计的,因为我在我的项目中也使用了 JNI。