我试图使我的应用程序的外观看起来像这样:
但是当我尝试做到这一点时,我得到了这样的结果:
这是我用来创建两个 JPanel 的代码以及如何添加按钮等......
//This is the panel that shows the image
appletRunningPanel = new ImagePanel();
appletRunningPanel.setSize(600, 300);
appletRunningPanel.validate();
//This is the panels that shows the 3 buttons
appletRunningPanel2 = new Panel(new GridLayout(1, 3));
appletRunningPanel2.setSize(600, 300);
appletRunningPanel2.add(test1);
appletRunningPanel2.add(test2);
appletRunningPanel2.add(test3);
appletRunningPanel2.validate();
//Then i add them to the applet with this:
add(appletRunningPanel);
add(appletRunningPanel2);
这是ImagePanel的代码
public class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel() {
setSize(600, 300);
try {
image = ImageIO.read(getClass().getResourceAsStream("/res/TCHLogo.png"));
} catch (IOException ex) {
// handle exception...
System.out.println(ex);
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
最佳答案
GridLayout 将拉伸(stretch)每个单元格中的组件以适应单元格的大小,如果您想避免这种拉伸(stretch),请将按钮添加到另一个面板并将该面板添加到 GridLayout
。
根据我的经验,用 Java 布局用户界面就是混合和匹配布局管理器以实现总体目标。有一些简化的管理器,例如 Mig Layout
对于你的例子,我会做这样的事情:
+----------------------------------------+
| panel1 |
|+--------------------------------------+|
|| panel2 ||
|+--------------------------------------+|
+----------------------------------------+
+----------------------------------------+
| panel3 |
|+-----------++-----------++------------+|
|| panel4 || panel5 || panel6 ||
|+-----------++-----------++------------+|
+----------------------------------------+
panel1
有BorderLayout
panel2
是您的ImagePanel
,并通过panel1.add(panel2, BorderLayout.CENTER) 添加到
panel1
;panel3
是您的GridLayout
。panel4
、panel5
和panel6
均为默认值 (FlowLayout
),并且每个JPanel
将包含三个按钮之一。
然后,您可以将其布局设置为 BorderLayout
并通过 getContentPane().add(panel1, BorderLayout.NORTH 添加
和 panel1
来将其添加到内容 Pane 中);panel3
通过 getContentPane().add(panel3, BorderLayout.SOUTH);
它并不完美,但它会为您带来更干净的外观。您可以添加更多内容以使事情看起来更好。我最喜欢的布局管理器之一是 BoxLayout
.
关于java - 我的 JPanel 没有按我想要的方式显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8125085/