java JPanel布局添加文本框并重新排列组件
我的Swing GUI有一些问题
现在看起来是这样的:
但我想把一些东西搬来搬去
- 首先我想要键盘下面的按钮
- 我想在键盘顶部添加一个文本字段,并在右侧添加submit按钮李>
我怎样才能做到这一点?我试着创建一个GridLayout,并按行、列坐标来划分位置,但似乎不起作用
private class Display extends JPanel {
Display() {
setPreferredSize(new Dimension(620, 420));
setBackground(new Color(250, 230, 180));
setFont(new Font("Serif", Font.BOLD, 20));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setStroke(new BasicStroke(3));
if (message != null) {
g.setColor(Color.RED);
g.drawString(message, 30, 40);
g.drawString("00:00", 30, 410);
}
}
}
private void createWindow() {
setJMenuBar(menuBarCreator());
// The ActionListener that will respond to button clicks.
ButtonHandler buttonHandler = new ButtonHandler();
// Create the subpanels and add them to the main panel.
display = new Display();
setLayout(new BorderLayout(3, 3));
add(display, BorderLayout.CENTER);
JPanel bottom = new JPanel();
bottom.setLayout(new GridLayout(1,1));
add(bottom, BorderLayout.NORTH);
// Add keyboard
JPanel keyboard = new JPanel();
JPanel keyboardHolder = new JPanel();
keyboard.setLayout(new GridLayout(2, 13));
keyboardHolder.setLayout(new GridLayout(1, 2));
for (char alphabet = 'a'; alphabet <= 'z'; alphabet++) {
JButton button = new JButton(String.valueOf(alphabet));
button.addActionListener(buttonHandler);
keyboard.add(button);
alphabetButtons.add(button);
}
keyboardHolder.add(keyboard, 0,0);
add(keyboardHolder, BorderLayout.SOUTH);
// Create three buttons, register the ActionListener to respond to clicks on the
// buttons, and add them to the bottom panel.
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(buttonHandler);
keyboard.add(submitButton);
JButton startButton = new JButton(GuiText.START.toString());
startButton.addActionListener(buttonHandler);
bottom.add(startButton);
JButton nextButton = new JButton(GuiText.NEXT.toString());
nextButton.addActionListener(buttonHandler);
bottom.add(nextButton);
JButton skipButton = new JButton(GuiText.SKIP.toString());
skipButton.addActionListener(buttonHandler);
bottom.add(skipButton);
JButton quit = new JButton(GuiText.QUIT.toString());
quit.addActionListener(buttonHandler);
bottom.add(quit);
setBackground(new Color(100, 0, 0));
nextButton.setEnabled(false);
skipButton.setEnabled(false);
}
# 1 楼答案
下面是camickr在对原始问题的评论中所写内容的一个具体例子。请注意,这不是唯一的可能性。有很多布局经理。我建议参观Laying Out Components Within a Container
代码的目的只是向您展示如何实现所需的布局
您需要在
Display
面板下面有三行,如下所示因此,“底部”面板包含三个面板,一个位于另一个之上
第一个面板是文本字段和“提交”面板
下面是“键盘”
键盘下面是其他按钮
请注意
JPanel
的默认布局管理器是java.awt.FlowLayout
,此布局管理器适用于包含“提交”按钮的面板,也适用于包含其他按钮的面板下面是running应用程序的屏幕截图