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

时间:2013-11-20 20:04:20

标签: java swing responsive-design

我在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 ________________

1 个答案:

答案 0 :(得分:3)

你可以使用你的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);
  }
}