我是初学者,做功课。我的按钮正在填充gridLayout中的整个单元格。我已经读过关于GridBagLayout但我的书中没有提到任何关于它的内容所以我认为我当前的代码只是出错了。老师一直试图帮助我,但我们无法弄清楚,所以我想我会在这里尝试。任何帮助,将不胜感激!这就是我所拥有的:
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();
}
});
}
}
答案 0 :(得分:3)
以下是Swing tutorial about GridLayout:
的引用GridLayout对象将组件放置在单元格网格中。每 component获取其单元格和每个单元格中的所有可用空间 是完全相同的大小。
如果你的书没有说出这么重要的东西,这本书很糟糕,我会建议你使用Swing教程。我很惊讶你的老师无法告诉你。
如果此行为不是您想要的,请选择其他布局管理器。 Swing教程提供了all standard ones的指南。