Java中JComboBox的定位

4
我想把一个 JComboBox 定位到下图所示的位置。我想知道是否有简单的代码可以实现这一点?
3个回答

3

Centered Combos

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 https://dev59.com/7Ww05IYBdhLWcg3wmC6_#7143398 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);
    }
}

谢谢。当我尝试使用JPanel添加图像时,使用这段代码它不会显示出来。 - Marcello

3

1

您可以使用MigLayout和行列约束,例如[max][min][max] - 这将把您的根面板分成一个3x3的网格,并在中间区域(即最小/最小)放置一个带有垂直流式布局的JPanel,您可以在其中添加组件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接