gpt4 book ai didi

Java Swing GridBagLayout : JLabel takes up too much space

转载 作者:行者123 更新时间:2023-12-02 12:30:07 24 4
gpt4 key购买 nike

我有一个带有三个按钮和一个标签的 JPanel。一个按钮和标签位于第一行,另外两个按钮位于第二行。我需要标签位于右上角,但这样做会导致标签意外增加并将两个向下按钮推到左侧。

public class UserInterface extends JFrame  {
int width;
int height;

JPanel panel;
public static void main(String[] args) {
run();
}
public UserInterface() {
setup();
}

private void setup() {
width=800;
height=600;

panel=new UserInterfacePanel();
getContentPane().add(panel, BorderLayout.NORTH);


setSize(width, height);

setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void run() {
UserInterface gui=new UserInterface();
gui.setVisible(true);
}
}

class UserInterfacePanel extends JPanel {
private JToggleButton startButton;
private JToggleButton stopButton;

private JButton homeStatusButton;
private JLabel timeStatusLabel;

public static void main(String[] args) {

}

public UserInterfacePanel() {
setup();
}

private void setup() {
setLayout(new GridBagLayout());

setupButtons();

timeStatusLabel=new JLabel();
timeStatusLabel.setMinimumSize(new Dimension(180,200));
timeStatusLabel.setPreferredSize(new Dimension(180,200));
timeStatusLabel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));

GridBagConstraints c1 = new GridBagConstraints();
c1.fill = GridBagConstraints.HORIZONTAL;

c1.weightx=0;
c1.weighty=0;
c1.anchor=GridBagConstraints.CENTER;
c1.gridx=0;
c1.gridy=0;
c1.insets=new Insets(20, 20, 250, 50);
add(homeStatusButton, c1);
c1.gridx=1;
c1.gridy=0;
c1.insets=new Insets(0, 50, 10, 10);
c1.weightx=1;
add(timeStatusLabel, c1);


GridBagConstraints c2=new GridBagConstraints();
c2.insets=new Insets(30,20,30,20);
c2.anchor=GridBagConstraints.CENTER;
c2.weightx=0.0;
c2.gridx=0;
c2.gridy=1;
add(startButton, c2);

c2.gridx=1;
c2.gridy=1;
add(stopButton, c2);
}

private void setupButtons() {
startButton=new JToggleButton("Start Button");
stopButton=new JToggleButton("Stop Button");

homeStatusButton=new JButton("OUT");
homeStatusButton.setBackground(Color.RED);
homeStatusButton.setForeground(Color.BLACK);
homeStatusButton.setSize(new Dimension(100, 20));
}
}

我不明白为什么会发生这种情况。看起来我隐含地说明了按钮的位置以及标签的位置。为什么标签变大并且按钮被推到左边。

enter image description here

最佳答案

but it's still too big of a label

您指定大小为 (180, 200),附加插图为 (250, 50)。

too big of a push for the buttons

所有组件都会使用这些约束,除非您每次向面板添加组件时都重置约束。

因此,标签的插图也可用于按钮,除非您重置插图。

另外,请记住 GridBagLayout 将在单元格内定位组件。所以第一列的单元格等于两个按钮的最大宽度。第二列的宽度将是标签的宽度,因为它是该列中最大的组件。

如果您希望开始/停止按钮放在一起,请先将它们添加到面板中,然后将按钮面板添加到 GridBagLayout 面板中。

关于Java Swing GridBagLayout : JLabel takes up too much space,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45313553/

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