gpt4 book ai didi

java - 我将如何在 Java Swing 中创建响应式布局

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:54:44 24 4
gpt4 key购买 nike

我在 swing JPanel 中显示键值对列表。键显示在 JLabel 中,值显示在 JTextField 中。面板上有足够的空间来显示 1 列或 2 列键值对,具体取决于父 JFrame 的大小。除非面板太小,否则我想显示 2 列键值对。然后我想切换到一栏。在不编写我自己的自定义布局管理器的情况下,这在 Swing 中是否可行?

将每个键值对放在它自己的面板上并将面板添加到 Flow Layout 会做我想做的事情,除了标签不会彼此对齐并且文本字段不会彼此对齐所以它看起来糟糕的。有更好的方法吗?

编辑:

这是它的样子。如果面板足够大,显示两列。否则显示一列。

2 列:

   Some Key _______________                Key 2 ________________ 
Another Key _______________ Yet Another Key ________________
Key 5 _______________ Key 6 ________________

1 列

       Some Key _______________                
Key 2 _______________
Another Key _______________
Yet Another Key _______________
Key 5 _______________
Key 6 ________________

最佳答案

您可以使用您的 FlowLayout 想法并仍然制作标签/文本字段阵容。向每个键/值面板添加一个支柱,该面板的大小是最长标签的大小,以强制文本字段在每个面板上向右移动相同的数量。像这样的东西:

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

public class Test implements Runnable
{
private String[] keys = {"One", "Twoooooo", "Three", "Four",
"Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Eleven", "Twelve"};
private String[] values = {"Apple", "Boy", "Cat", "Denmark",
"Elephant", "Foo", "Hello", "Igloo",
"Jug", "Kangaroo", "Lip", "Now"};

public static void main(String[] args)
{
SwingUtilities.invokeLater(new Test());
}

public void run()
{
JPanel panel = new JPanel(new FlowLayout());
GridBagConstraints gbc;
JTextField textField = null;
int maxWidth = 0;
JLabel[] labels = new JLabel[keys.length];

for (int i = 0; i < keys.length; i++)
{
labels[i] = new JLabel(keys[i]);
maxWidth = Math.max(labels[i].getPreferredSize().width, maxWidth);
}

JPanel[] panels = new JPanel[keys.length];

for (int i = 0; i < keys.length; i++)
{
panels[i] = new JPanel(new GridBagLayout());

gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(1,1,1,1);
panels[i].add(Box.createHorizontalStrut(maxWidth), gbc);

gbc.gridy = 1;
panels[i].add(labels[i], gbc);

textField = new JTextField(10);
textField.setText(values[i]);
gbc.gridx = 1;
panels[i].add(textField, gbc);

panel.add(panels[i]);
}

JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.setSize(240, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

关于java - 我将如何在 Java Swing 中创建响应式布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20105833/

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