我正在嘗試創建Pair Game。我創建了2個JPanel:第一個用於遊戲地圖(100個按鈕),第二個用於統計。問題是我有像左圖片一樣的計時器和計數器的部署,但我想讓它像在正確的圖片(我在繪畫中編輯它)。我應該使用哪種佈局?我嘗試了很多解決方案,但沒有爲我工作。另外,如果我設置爲null經理的JPanel dissapear在Jpanel中設置組件
public class PairGame extends JFrame implements ActionListener{
JLabel counterLabel, timerLabel;
JMenuBar menuBar;
JMenu file, help;
JMenuItem fileNew, fileExit, helpAbout;
JPanel gamePanel, statisticsPanel;
JToggleButton buttons[];
ArrayList <Integer> values;
int temp=0, counter=0;
void createMenuBar()
{
file = new JMenu("File");
fileNew = new JMenuItem("New");
fileNew.addActionListener(this);
fileNew.setAccelerator(KeyStroke.getKeyStroke("ctrl N"));
fileExit = new JMenuItem("Exit");
fileExit.addActionListener(this);
fileExit.setAccelerator(KeyStroke.getKeyStroke("ctrl Q"));
file.add(fileNew);
file.add(fileExit);
file.setMnemonic('f');
help = new JMenu("Help");
helpAbout = new JMenuItem("About");
helpAbout.addActionListener(this);
helpAbout.setAccelerator(KeyStroke.getKeyStroke("ctrl H"));
help.add(helpAbout);
help.setMnemonic('h');
menuBar = new JMenuBar();
menuBar.add(file);
menuBar.add(help);
setJMenuBar(menuBar);
}
public void createGameMap()
{
gamePanel = new JPanel(new GridLayout(10,10));
values = new ArrayList<Integer>();
for(int i=1; i<=50; i++)
values.add(i);
for(int i=51; i<=100; i++)
values.add(i-50);
Collections.shuffle(values);
buttons = new JToggleButton[100];
for(int i=0; i<100; i++)
{
buttons[i] = new JToggleButton(""+(i+1));
buttons[i].setName(String.valueOf(values.toArray()[i]));
buttons[i].addActionListener(this);
gamePanel.add(buttons[i]);
}
gamePanel.setBounds(0,0,550,400);
add(gamePanel);
}
public void createStatisticsPanel()
{
statisticsPanel = new JPanel();
counterLabel = new JLabel("Counter: "+counter);
timerLabel = new JLabel("Timer: ");
statisticsPanel.add(counterLabel);
statisticsPanel.add(timerLabel);
statisticsPanel.setBounds(0,410,540,400);
add(statisticsPanel);
}
PairGame()
{
setTitle("Pair Game");
setSize(565,600);
setLocation(400,100);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createMenuBar();
createGameMap();
createStatisticsPanel();
setVisible(true);
}
public static void main(String[] args)
{
new PairGame();
}
對於'statisticsPanel',您可以使用['BoxLayout'](https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html),['GridLayout'](https:// docs.oracle.com/javase/tutorial/uiswing/layout/grid.html),['GridBagLayout'](https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html)甚至[ 'BorderLayout'](https://docs.oracle.com/javase/tutorial/uiswing/layout/border.html)。在這種情況下,由我個人的喜好來命名。 –
考慮發佈[MCVE] – c0der
請參閱http://stackoverflow.com/help/someone-answers – c0der