按钮填充了GridLayout中的整个单元格,Java
我是初学者,正在做作业。我的按钮填满了gridLayout中的整个单元格。我读过GridBagLayout,但我的书中没有提到任何关于它的内容,所以我认为我当前的代码有一个错误。老师一直在试图帮助我,但我们无法理解,所以我想我会在这里试试。任何帮助都将不胜感激!以下是我所拥有的:按钮填充了GridLayout中的整个单元格,Java,java,swing,layout-manager,grid-layout,Java,Swing,Layout Manager,Grid Layout,我是初学者,正在做作业。我的按钮填满了gridLayout中的整个单元格。我读过GridBagLayout,但我的书中没有提到任何关于它的内容,所以我认为我当前的代码有一个错误。老师一直在试图帮助我,但我们无法理解,所以我想我会在这里试试。任何帮助都将不胜感激!以下是我所拥有的: package riddle; import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Riddle imple
package riddle;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Riddle implements ActionListener {
private final String LABEL_TEXT = "Why did the chicken cross the road?";
JFrame frame;
JPanel contentPane;
JLabel label, label1;
JButton button;
JButton button1;
private static int i;
public Riddle() {
/* Create and set up the frame */
frame = new JFrame(LABEL_TEXT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* Create a content pane with a GridLayout and empty borders */
contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 2, 10, 5));
/* Create and add label that is centered and has empty borders */
label = new JLabel("Why did the chicken cross the road?");
label.setAlignmentX(JButton.LEFT_ALIGNMENT);
label.setBorder(BorderFactory.createEmptyBorder(20, 50, 20, 50));
contentPane.add(label);
label1 = new JLabel(" ");
label1.setAlignmentX(JButton.LEFT_ALIGNMENT);
label1.setBorder(BorderFactory.createEmptyBorder(20, 50, 20, 50));
contentPane.add(label1);
/* Create and add button that is centered */
button = new JButton("Answer");
button.setAlignmentX(JButton.RIGHT_ALIGNMENT);
button.setActionCommand("Show Answer");
button.addActionListener(this);
contentPane.add(button);
/* Add content pane to frame */
frame.setContentPane(contentPane);
/* Size and then display the frame */
frame.pack();
frame.setVisible(true);
}
/** Handle button click action event
* pre:
* post: clicked button shows answer
*/
public void actionPerformed(ActionEvent event) {
String eventName = event.getActionCommand();
if (eventName.equals("Show Answer")) {
label1.setText("To get to the other side. ");
button.setText("Answer");
button.setActionCommand("Answer");
}
}
/**
* Create and show the GUI
*/
private static void runGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
Riddle greeting = new Riddle();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
runGUI();
}
});
}
}
以下是一段引用自:
GridLayout对象将组件放置在单元格网格中。每个
组件获取其单元格内的所有可用空间,以及每个单元格
大小完全一样
如果你的书没有讲述这么重要的事情,那就是一本糟糕的书,我建议你改用Swing教程。我很惊讶你的老师没能告诉你
如果此行为不是您想要的,请选择其他布局管理器。Swing教程中有一个有关的指南 谢谢。是的,我正在使用的这本书是一本Java编程指南,它只讨论了行和列。我正在研究的问题甚至是使用网格布局,但是它需要看起来像什么的图片,使得它看起来像按钮和单元格之间有一个空白。另外,澄清一下,不是我的老师,而是老师的助手,我提出这个问题的原因是想让你们知道我在努力,而不是不做任何研究就把我的问题扔到这里。无论如何,非常感谢,很抱歉我的问题太蹩脚了:(使用构造函数的hgap和vgap参数设置边距不是问题。但是所有单元格共享相同的hgap和vgap。另请参阅。