gpt4 book ai didi

java - 如何将多个元素相互对齐?

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

我在将 Swing 元素流彼此对齐时遇到困难。使用 GridLayout 对我没有帮助,因为它将屏幕划分为具有相同大小的行。我需要将一个组件放置到每一行,下一个组件应该位于最后一个组件的最底部。

我的问题是,如果问题的选择超过一行,这种布局会将它们挤到行中,并且图片和问题“3+3?”之间存在巨大差距

最佳答案

您可以使用GridBagLayout来实现此目的。这是非常容易使用。这是一个示例实现。

enter image description here

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

class MyFrame extends JFrame {

public MyFrame() {
JPanel panel = new JPanel(new GridBagLayout());

JLabel image = new JLabel();
image.setIcon(new ImageIcon(getClass().getResource("/image.png")));

JLabel question = new JLabel("3 + 3 = ?");

JRadioButton rb1 = new JRadioButton("5");
JRadioButton rb2 = new JRadioButton("3");
JRadioButton rb3 = new JRadioButton("6");
JRadioButton rb4 = new JRadioButton("9");
JRadioButton rb5 = new JRadioButton("23");

GridBagConstraints c = new GridBagConstraints();

c.gridx = 0;//set the x location of the grid for the next component
c.gridy = 0;//set the y location of the grid for the next component
panel.add(image,c);

c.gridy = 1;//change the y location
c.anchor=GridBagConstraints.WEST;//left align components after this point
panel.add(question,c);

c.gridy = 2;//change the y location
panel.add(rb1,c);

c.gridy = 3;//change the y location
panel.add(rb2,c);

c.gridy = 4;//change the y location
panel.add(rb3,c);

c.gridy = 5;//change the y location
panel.add(rb4,c);

c.gridy =6;//change the y location
panel.add(rb5,c);

this.getContentPane().add(panel);

this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
}

public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
myFrame.setVisible(true);
}

}

引用文献:https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

关于java - 如何将多个元素相互对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32628964/

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