gpt4 book ai didi

java - 如何使 Swing 组件具有不同的尺寸

转载 作者:行者123 更新时间:2023-12-01 15:21:09 26 4
gpt4 key购买 nike

如何在java中为Swing组件制定特定的尺寸? gui 应该看起来像这样...

+++++++++++++++++
+ TextField +
+++++++++++++++++
+ +
+ TextPane +
+ +
+++++++++++++++++
+Button +Button +
+++++++++++++++++

我尝试过 BorderLayoutGridLayout、嵌套 JPanels 等,但我无法获得一个好看的 gui,其中 JButtons 不像砖 block ,JTextField 也不是文本大小的三倍。

最佳答案

部分取决于您希望如何分配额外空间。该 GUI 为文本字段和文本区域提供了额外的宽度,同时保持按钮居中。文本区域具有额外的高度。

Basic Layout

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.*;

public class BasicLayout {

BasicLayout() {
JPanel gui = new JPanel(new BorderLayout(2,2));

gui.add(new JTextField(), BorderLayout.PAGE_START);
gui.add(new JTextArea(3,15));

JPanel controls = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
controls.add(new JButton("Button1"));
controls.add(new JButton("Button2"));

gui.add(controls, BorderLayout.PAGE_END);

JOptionPane.showMessageDialog(null, gui);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new BasicLayout();
}
});
}
}

更新

起初我以为你指的是中间部分的JTextArea,然后我仔细一看。 JTextPane 的大小调整稍微复杂一些,因为它不接受构造函数中的大小提示。为此,我们可以调整容器的首选大小(在本例中为 JScrollPane

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.*;

public class BasicLayout {

BasicLayout() {
JPanel gui = new JPanel(new BorderLayout(2,2));

gui.add(new JTextField(), BorderLayout.PAGE_START);
JTextPane text = new JTextPane();
JScrollPane scroll = new JScrollPane(text);
Dimension d = text.getPreferredSize();
scroll.setPreferredSize(new Dimension(d.width, d.height*3));
gui.add(scroll);

JPanel controls = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
controls.add(new JButton("Button1"));
controls.add(new JButton("Button2"));

gui.add(controls, BorderLayout.PAGE_END);
JOptionPane.showMessageDialog(null, gui);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new BasicLayout();
}
});
}
}

关于java - 如何使 Swing 组件具有不同的尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10906885/

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