gpt4 book ai didi

java - 按钮填满了 GridLayout 中的整个单元格,Java

转载 作者:塔克拉玛干 更新时间:2023-11-02 18:58:59 24 4
gpt4 key购买 nike

我是初学者,正在做作业。我的按钮填满了 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();
}
});
}
}

最佳答案

这是来自 Swing tutorial about GridLayout 的引述:

A GridLayout object places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size.

如果您的书没有讲述如此重要的事情,那它就是一本烂书,我建议改用 Swing 教程。我很惊讶你的老师没能告诉你。

如果此行为不是您想要的,请选择另一个布局管理器。 Swing 教程有一个指南 all standard ones .

关于java - 按钮填满了 GridLayout 中的整个单元格,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9470072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com