4

我想JComboBox按照下图所示的方式定位 a。我想知道是否有简单的代码来实现这一点?

在此处输入图像描述

4

3 回答 3

3

使用适当的布局管理器,例如BoxLayout. 有关详细信息,请参阅如何使用 BoxLayout

于 2013-01-09T17:46:56.797 回答
3

居中连击

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

public class CenteredCombos {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                String[] values = {"Dog","Cat"};
                // put the controls in a single column, with a little space.
                JPanel controlPanel = new JPanel(new GridLayout(0,1,5,5));
                for (int ii=0; ii<4; ii++) {
                    controlPanel.add(new JComboBox(values));
                }

                // the GUI as seen by the user (without frame)
                // The GBL is used to center the controlPanel
                JPanel gui = new JPanel(new GridBagLayout());
                gui.setBorder(new EmptyBorder(2, 3, 2, 3));
                gui.add(controlPanel);

                // Make the BG panel more clear..
                gui.setBackground(Color.WHITE);

                JFrame f = new JFrame("Demo");
                f.add(gui);
                // Ensures JVM closes after frame(s) closed and
                // all non-daemon threads are finished
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                // See http://stackoverflow.com/a/7143398/418556 for demo.
                f.setLocationByPlatform(true);

                // ensures the frame is the minimum size it needs to be
                // in order display the components within it
                f.pack();
                // should be done last, to avoid flickering, moving,
                // resizing artifacts.
                f.setVisible(true);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}
于 2013-01-09T17:55:31.820 回答
1

您可以将MigLayout与行和列约束一起使用,例如[max][min][max]- 将您的根面板划分为具有“贪婪”边框的 3x3 网格,并在中间区域(即分钟/分钟)放置一个具有垂直流布局的 JPanel ,其中你可以添加你的组件

于 2013-01-09T17:49:16.893 回答