大多数时候,我更喜欢使用 java 的内置工具,而不是为这种简单的情况混合更复杂的库和依赖项。我认为,当您可以通过这样的微不足道的努力来实现解决方案时,就不需要使用 MIG 等第三方库。这种偏好来自您所处的情况:没有多少人使用购买的工具,因此您无法从社区获得如此多的帮助。
我知道这个问题询问了MigLayout,但我更愿意表明对于这种简单的情况没有必要使用它。 MIG 库很丰富,并且有一些有用的组件可以让您的生活更轻松,但在布局方面我更喜欢纯 java。
使用纯BorderLayout 和GridLayout 对布局进行采样:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
public class TestMain {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
JFrame f = new JFrame();
f.setBounds(50, 50, 500, 400);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.add(createSpacerPanel(10, 10), BorderLayout.NORTH);
f.add(createSpacerPanel(10, 10), BorderLayout.SOUTH);
f.add(createSpacerPanel(10, 10), BorderLayout.EAST);
f.add(createSpacerPanel(10, 10), BorderLayout.WEST);
f.add(new MainPanel());
f.setVisible(true);
}
private static JPanel createSpacerPanel(int width, int height){
JPanel spacer = new JPanel();
spacer.setPreferredSize(new Dimension(width, height));
return spacer;
}
}
class MainPanel extends JPanel{
public MainPanel() {
init();
}
private void init() {
JPanel northPanel = new JPanel(new BorderLayout(10, 10));
northPanel.setPreferredSize(new Dimension(100, 60));
northPanel.add(new JLabel("Class Expression: "), BorderLayout.NORTH);
JTextArea classExpressionTextArea = new JTextArea();
classExpressionTextArea.setSize(10, 40);
northPanel.add(new JScrollPane(classExpressionTextArea), BorderLayout.CENTER);
JButton calculateButton = new JButton("Calculate");
northPanel.add(calculateButton, BorderLayout.EAST);
JPanel definitionPanel = new JPanel(new BorderLayout(10,10));
definitionPanel.add(new JLabel("Definitions Found: "), BorderLayout.NORTH);
JTextArea definitionsTextArea = new JTextArea();
definitionPanel.add(new JScrollPane(definitionsTextArea), BorderLayout.CENTER);
JPanel signaturePanel = new JPanel(new BorderLayout(10,10));
signaturePanel.add(new JLabel("Target Signature: "), BorderLayout.NORTH);
JTextArea targetTextArea = new JTextArea();
signaturePanel.add(new JScrollPane(targetTextArea), BorderLayout.CENTER);
GridLayout gridLayout = new GridLayout(1,1,10,10);
JPanel centerPanel = new JPanel(gridLayout);
centerPanel.add(definitionPanel);
centerPanel.add(signaturePanel);
setLayout(new BorderLayout(10,10));
add(northPanel, BorderLayout.NORTH);
add(centerPanel, BorderLayout.CENTER);
}
}
以及完全可调整大小的输出:
使用GridBagLayout 可以实现相同的效果,这与MigLayout 在考虑布局和定位以及跨越网格单元格上的组件的方式相似。
希望这会有所帮助。