我正在研究一些GUI对象的嵌套。到目前为止,我已经完成了大部分工作,但最新的部分我还没弄清楚。这可能是一个简单的问题,我不认为嵌套的深度是导致问题的,但我会列出我所拥有的以防万一。
到目前为止,我的JFrame
包含一个JPanel
,其JTabbedPane
,JTabbedPane
中有JPanels
个JPanels
。我目前正在处理其中一个JSplitPane
- 它包含一个JScrollPane
,其中包含JSplitPane
和另一个JSplitPane
。第二个JScrollPane
有两个JScrollPane
个。其中一个JPanel
有一个JPanel
。
直到最后JScrollPane
,这一切都正常工作,我添加了一个背景,作为测试它的方法,看看它是否正常工作。我的问题是背景基本上显示为JPanel
内的边框,窗格内部是灰色的,就像没有背景一样。
以下是我的一些代码 - 如果有人认为它会有用,我可以提供更多代码。
这是JTabbedPane
内的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);
}
}
这是给我带来问题的小组。
{{1}}
有人看到我做错了吗?我对Java GUI组件没有太多经验,并且非常感谢任何人提供的任何帮助。
答案 0 :(得分:2)
toolContainer = new JScrollPane();
toolContainer.add(toolPanel);
您没有向JScrollPane添加组件。该组件被添加到"视口"滚动窗格。
您可以使用:
toolContainer = new JScrollPane( toolPanel );
或
toolContainer = new JScrollPane();
toolContainer.setViewportView(toolPanel);
另外,你不应该使用:
setSize(w, h);
组件的布局管理器将根据添加到面板的comopnents确定组件的首选大小。
如果您正在进行某种自定义绘制,那么您应该覆盖ToolPanel的getPreferredSize()
方法以返回适当的大小。