我正在尝试将JScrollPane(createTeamScrollPane)添加到我拥有的JPanel(createTeamPanel)中。我有一个框架,其中的BorderLayout的NORTH部分被JPanel使用,名为tabMenu,然后CENTER部分我希望我的'createTeamPanel'具有此滚动功能,因为它将具有比我可以容纳的内容更多的内容。屏幕一次。然后,我将两个面板都添加到框架中。当前,代码按原样运行,但窗口显示为空白。调整窗口大小后,我会在框架的北部分看到3个按钮(为什么会这样?),当我单击“创建团队”时,它会弹出我期望的JLabel和JButton列表。看到任何滚动条吗?
public static void main (String args[]) {
JFrame frame = new JFrame();
frame.setTitle("v0.01");
frame.setSize(800, 800);
//frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel tabMenu = new JPanel();
JPanel createTeamPanel = new JPanel();
createTeamPanel.setLayout(new BoxLayout(createTeamPanel, BoxLayout.Y_AXIS));
createTeamPanel.setSize(800, 700);
createTeamPanel.setVisible(showCreateTeamPanel);
createTeamPanel.setBackground(Color.gray);
JScrollPane createTeamScrollPane = new JScrollPane(createTeamPanel);
createTeamScrollPane.setBounds(50, 50, 200, 500);
createTeamScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
createTeamScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
createTeamScrollPane.setPreferredSize(new Dimension(500,500));
//createTeamPanel.add(createTeamScrollPane);
List<Player> teamList = MockTeams.initTeam();
int xcoord = 100;
int ycoord = 50;
for(Player player : teamList) {
JLabel label = new JLabel(player.getName());
label.setBounds(xcoord, ycoord, Constants.buttonWidth, Constants.buttonHeight);
JButton addToTeamBtn = new JButton("Add to team");
addToTeamBtn.setBounds(xcoord + 100, ycoord, Constants.buttonWidth, Constants.buttonHeight);
addToTeamBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myTeam.add(player);
addToTeamBtn.setEnabled(false);
}
});
createTeamPanel.add(label);
//createTeamFrame.add(label);
createTeamPanel.add(addToTeamBtn);
//createTeamFrame.add(addToTeamBtn);
ycoord += 50;
}
JButton createTeamBtn = new JButton("Create Team");
createTeamBtn.setBounds(0,0,150,20);
createTeamBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Hide/Show Create team panel
if (!showCreateTeamPanel) {
showCreateTeamPanel = true;
createTeamPanel.setVisible(showCreateTeamPanel);
} else {
showCreateTeamPanel = false;
createTeamPanel.setVisible(showCreateTeamPanel);
}
}
});
JButton manageTeamBtn = new JButton("Team Statistics");
manageTeamBtn.setBounds(100,150,150,40);
JButton resetBtn = new JButton("Reset Season");
resetBtn.setBounds(100,200,150,40);
tabMenu.add(createTeamBtn);
tabMenu.add(manageTeamBtn);
tabMenu.add(resetBtn);
mainPanel.add(tabMenu, BorderLayout.NORTH);
mainPanel.add(createTeamPanel, BorderLayout.CENTER);
frame.add(mainPanel);
}
预期的结果是在createTeamPanel上看到滚动功能,但它不存在。
答案 0 :(得分:0)
已修复:我可以通过以下方式将JScrollPane添加到mainPanel中:
mainPanel.add(createTeamScrollPane,BorderLayout.CENTER);