gpt4 book ai didi

java - 如何使按钮展开Java

转载 作者:行者123 更新时间:2023-11-29 08:07:41 25 4
gpt4 key购买 nike

我正在尝试创建一个 Java Applet,我在 Java 网站上四处寻找,发现了一个我编辑过的很好的例子。

在这个例子中有 3 个按钮,一个像页眉,一个像页脚和一个像 body 一样的人。我的问题是,中间(正文)按钮不会完全展开。

如果你运行这段代码,你就会明白我的意思。

import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;

public class main {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;

public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}

JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}


button = new JButton("hi");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
c.ipady = 40;
pane.add(button, c);

button = new JButton("Hello, i will not expand");
c.fill = GridBagConstraints.BOTH;
c.weighty = 1.0; //request any extra vertical space
c.weightx=1.0;
c.anchor = GridBagConstraints.CENTER; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.gridx = 1; //aligned with button 2
c.gridy = 1; //third row
pane.add(button, c);


button = new JButton("fr");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.gridx = 1; //aligned with button 2
c.gridwidth = 2; //2 columns wide
c.gridy = 2; //third row
pane.add(button, c);
}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("main");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane.
addComponentsToPane(frame.getContentPane());

//Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

enter image description here

最佳答案

看起来不是中间按钮的错,而是底部按钮没有展开,如果你这样设置底部按钮 c.fill = GridBagConstraints.BOTH; 那么它会占用空的下面的空间。

你想让中间大一点吗?您可能希望将底部按钮的权重更改为 .5c.weighty = .5;//请求任何额外的垂直空间
看看这是否是您要找的东西?

如果你想让中间比顶部和底部大得多,你可能需要制作更多的网格空间,所以不要用 1,1,1,试试 1,3,1 等等

关于java - 如何使按钮展开Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10019181/

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