我看过多个类似的帖子,但似乎没有一个像我一样的问题,看起来相对简单。我有以下代码:
public PlayScreen(Player player){
this.player = player;
playScreen = new JPanel();
playScreen.setLayout(new BorderLayout());
setTowerButtons();
playScreen.add(towerButtons, BorderLayout.EAST); //line 6
setDetailLabels();
playScreen.add(detailPanel, BorderLayout.WEST);
setMap("map.png");
playScreen.add(new JButton("hello"), BorderLayout.CENTER); //line 10
playScreen.setVisible(true);
}
public class View {
private JFrame frame;
private Container contentPane;
private Player player;
private LoadScreen loadScreen;
private PlayScreen playScreen;
public View(Player player){
frame = new JFrame("Display");
contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());
this.player = player;
frame.setVisible(true);
frame.pack();
}
public void makeLoadScreen(){
loadScreen = new LoadScreen();
contentPane.add(loadScreen.getLoadScreen(), BorderLayout.CENTER);
frame.pack();
}
public void makePlayScreen(Player player){
contentPane.remove(loadScreen.getLoadScreen());;
playScreen = new PlayScreen(player);
contentPane.add(playScreen.getPlayScreen());
frame.pack();
}
public class LoadScreen{
private JPanel loadScreen;
public LoadScreen(){
loadScreen = new JPanel();
JButton play = new JButton("Play");
JButton load = new JButton("Load");
loadScreen.setLayout(new GridLayout(2,1,0,0));
loadScreen.add(play);
loadScreen.add(load);
play.addActionListener(new OpenActionListener());
load.addActionListener(new LoadActionListener());
}
public class OpenActionListener implements ActionListener{
public void actionPerformed(ActionEvent e){
makePlayScreen(player);
}
}
}
}
首先创建View类。我手动调用makeLoadScreen()方法(虽然我稍后会更改它以自动执行此操作),这将创建嵌套类中描述的LoadScreen。这给出了两个按钮,播放和加载的视图。单击播放然后创建播放屏幕,问题出在那里。
运行时,detailPanel始终按预期显示在左上角。但是,TowerButtons面板消失,并显示“hello”按钮,填满了屏幕的其余部分。如果我切换第6行和第10行,“hello”按钮消失,并显示towerButtons面板,填满屏幕的其余部分。
相反,我想在右侧显示towerButtons,在此面板和detailPanel之间使用“hello”按钮。
编辑:添加其余代码,应该早点完成,对不起! Edits2:问题原来是“towerButtons”,与JPanel的覆盖无关。
答案 0 :(得分:0)
我想在右侧显示towerButtons,在此面板和detailPanel之间使用“hello”按钮。
问题可能在你的代码中的其他地方,所以我认为这不应该对你有所帮助,但在这里:
public class Example extends JFrame {
Example() {
JPanel playScreen = new JPanel();
playScreen.setLayout(new BorderLayout());
JPanel towerButtons = new JPanel();
towerButtons.add(new JLabel("towerButtons"));
playScreen.add(towerButtons, BorderLayout.EAST);
JPanel detailPanel = new JPanel();
detailPanel.add(new JLabel("detailPanel"));
playScreen.add(detailPanel, BorderLayout.WEST);
playScreen.add(new JButton("hello"), BorderLayout.CENTER);
add(playScreen);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new Example();
}
}