我目前正在為一個小型游戲專案制作 GUI,但我在鍵盤布局方面遇到了問題,特別是主行和底行。我完全錯過了查看我的代碼,但我有這段代碼:
home = new JButton[homeRow.length];
JPanel homekeys = new JPanel(new GridLayout(1, homeRow.length));
for(int i = 0; i < homeRow.length; i )
{
JButton homesize = new JButton(homeRow[i]);
homesize.setSize(50, 50);
home[i] = homesize;
keyboard.add(home[i]);
}
keyboard.add(homekeys);
bottom = new JButton[bottomRow.length];
JPanel bottomkeys = new JPanel(new GridLayout(1, bottomRow.length));
for(int i = 0; i < bottomRow.length; i )
{
JButton bottomsize = new JButton(bottomRow[i]);
bottomsize.setSize(50, 50);
bottom[i] = bottomsize;
keyboard.add(bottom[i]);
}
keyboard.add(topkeys);
keyboard.add(topkeys)應該在哪里keyboard.add(bottomkeys),盡管它正是我想要的格式:

但是當我將其更改為 時keyboard.add(bottomkeys),出現了一種奇怪的格式:

為什么當我將其更改為 use 時它的格式會奇怪,我將bottomkeys如何解決這個問題?
這是整個代碼:
import javax.swing.*;
import java.awt.*;
public class GameGUI extends JFrame
{
private final JPanel letters;
private final JPanel keyboard;
private final String[] topRow = {"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"};
private final String[] homeRow = {"A", "S", "D", "F", "G", "H", "J", "K", "L"};
private final String[] bottomRow = {"Enter", "Z", "X", "C", "V", "B", "N", "M", "Backspace"};
private final JButton[] top, home, bottom; // buttons for rows
public WordleGUI()
{
this.setSize(350,400);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
letters = new JPanel();
letters.setLayout(new GridLayout(6, 5));
for(int i = 0; i < 30; i )
letters.add(new JTextField());
keyboard = new JPanel();
keyboard.setLayout(new GridLayout(3, 1));
// top row
top = new JButton[topRow.length];
JPanel topkeys = new JPanel(new GridLayout(1, topRow.length));
for(int i = 0; i < topRow.length; i )
{
JButton topsize = new JButton(topRow[i]);
topsize.setSize(50, 50);
top[i] = topsize;
keyboard.add(top[i]);
}
keyboard.add(topkeys);
// home row
home = new JButton[homeRow.length];
JPanel homekeys = new JPanel(new GridLayout(1, homeRow.length));
for(int i = 0; i < homeRow.length; i )
{
JButton homesize = new JButton(homeRow[i]);
homesize.setSize(50, 50);
home[i] = homesize;
keyboard.add(home[i]);
}
keyboard.add(homekeys);
bottom = new JButton[bottomRow.length];
JPanel bottomkeys = new JPanel(new GridLayout(1, bottomRow.length));
for(int i = 0; i < bottomRow.length; i )
{
JButton bottomsize = new JButton(bottomRow[i]);
bottomsize.setSize(50, 50);
bottom[i] = bottomsize;
keyboard.add(bottom[i]);
}
keyboard.add(bottomkeys); // weird formatting occuring here
this.getContentPane().add(letters, BorderLayout.NORTH);
this.getContentPane().add(keyboard, BorderLayout.SOUTH);
this.setVisible(true);
}
public static void main(String[] args)
{
new GameGUI();
}
}
uj5u.com熱心網友回復:
您正在創建三個面板topkeys、homekeys和buttomkeys ,但實際上并沒有按預期使用它們。將按鈕添加到這些而不是鍵盤面板上。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/469509.html
