我正在研究 GUI 对象的一些嵌套。到目前为止,我已经完成了大部分工作,但最新的部分我还无法弄清楚。这可能是一个简单的问题,我不认为嵌套的深度导致了这个问题,但我会列出我所拥有的,以防万一。
到目前为止,我有一个JFrame
,其中包含一个JPanel
,其中有一个JTabbedPane
,这个JTabbedPane
有2个其中的JPanels
。我目前正在开发其中一个 JPanels
- 它包含一个 JSplitPane
,其中包含一个 JScrollPane
和另一个 JSplitPane
。第二个 JSplitPane
有两个 JScrollPane
。其中一个 JScrollPane
有一个 JPanel
。
直到最后一个 JPanel
为止,这一切都工作正常,我添加了一个背景,只是作为测试它是否正常工作的一种方法。我的问题是背景基本上显示为 JScrollPane
内的边框, Pane 内部是灰色的,就像没有背景一样。
这是我的一些代码 - 如果有人认为有用,我可以提供更多代码。
这是 JTabbedPane
内的 JPanel
。
public class MapEditor extends JPanel{
int height, width;
final int DIVIDER_SIZE = 7;
final int HORIZONTAL_DIVIDER_PLACE = 300;
final int VERTICAL_DIVIDER_PLACE = 200;
//side bar divider separates main page and left (vertical divider)
//side bar division separates top and bottom of sidebar (horizontal divider)
JSplitPane sideBarDivider;
JSplitPane sideBar;
//scroll pane to hold tiles panel, map panel
JScrollPane toolContainer;
JScrollPane tileContainer;
JScrollPane mapContainer;
//panels held inside JScrollPanes above
JPanel toolPanel;
JPanel tilePanel;
JPanel mapPanel;
public MapEditor(int w, int h){
this.width = w;
this.height = h;
setLayout(new BorderLayout());
//we can just pass the final variables in here because it's in the top left
toolPanel = new ToolPanel(HORIZONTAL_DIVIDER_PLACE,
VERTICAL_DIVIDER_PLACE);
sideBar = splitScreen();
add(sideBar);
}
//main split between map and tools/tiles
public JSplitPane splitScreen(){
mapContainer = new JScrollPane();
sideBar = buildSideBar();
//add map container and sidebar
sideBarDivider = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
sideBar, mapContainer);
sideBarDivider.setSize(width, height);
//set divider size and position
sideBarDivider.setDividerLocation(HORIZONTAL_DIVIDER_PLACE);
sideBarDivider.setDividerSize(DIVIDER_SIZE);
return sideBarDivider;
}
//small split between tools and tiles
public JSplitPane buildSideBar(){
toolContainer = new JScrollPane();
toolContainer.add(toolPanel);
tileContainer = new JScrollPane();
//add tile & tool containers
sideBar = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
toolContainer, tileContainer);
//set divider size and position
sideBar.setDividerSize(DIVIDER_SIZE);
sideBar.setDividerLocation(VERTICAL_DIVIDER_PLACE);
return sideBar;
}
}
这个面板给我带来了问题。
public class ToolPanel extends JPanel{
int width, height;
public ToolPanel(int w, int h){
this.width = w;
this.height = h;
setLayout(new BorderLayout());
setSize(w, h);
setBackground(Color.BLACK);
}
}
有人看到我做错了什么吗?我对 Java GUI 组件不太有经验,并且希望任何人提供帮助。
最佳答案
toolContainer = new JScrollPane();
toolContainer.add(toolPanel);
您不向 JScrollPane 添加组件。该组件将添加到滚动 Pane 的“视口(viewport)”。
您可以使用:
toolContainer = new JScrollPane( toolPanel );
或
toolContainer = new JScrollPane();
toolContainer.setViewportView(toolPanel);
此外,您不应该使用:
setSize(w, h);
组件的布局管理器将根据添加到面板的组件来确定组件的首选尺寸。
如果您正在进行某种自定义绘画,那么您应该重写 ToolPanel 的 getPreferredSize()
方法以返回适当的尺寸。
关于java - 将 JPanel 添加到 JSplitPane 中的 JScrollPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24049558/