简体   繁体   English

在JPanel中放置JLabel

[英]Position JLabel within JPanel

I want to position a JLabel within a JPanel , so that it appears at the top of the window. 我想在JPanel放置一个JLabel ,以便它出现在窗口的顶部。 I then want to position two drop-down menu below that so that the user can choose from two sets of options. 然后,我想在其下方放置两个下拉菜单,以便用户可以从两组选项中进行选择。

How would I go about positioning these elements? 我将如何定位这些元素?

Here's a JLabel title with two JComboBoxes. 这是带有两个JComboBoxes的JLabel标题。 I have no idea what else you mean by a "drop-down menu". 我不知道“下拉菜单”还意味着什么。

下拉布局

  1. I created a JPanel with a BorderLayout to hold the GUI. 我创建了一个带有BorderLayout的JPanel来容纳GUI。

  2. The title is a JLabel inside of a JPanel using the default FlowLayout. 标题是使用默认FlowLayout的JPanel内部的JLabel。

  3. The JComboBoxes are inside of a JPanel using the default FlowLayout. JComboBoxes使用默认的FlowLayout在JPanel内部。

Here's the code: 这是代码:

package com.ggl.testing;

import java.awt.BorderLayout;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class DropDownLayout implements Runnable {

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

    @Override
    public void run() {
        JFrame frame = new JFrame("Drop Down Layout");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        panel.add(createTitlePanel(), BorderLayout.NORTH);
        panel.add(createDropDownPanel(), BorderLayout.CENTER);

        frame.add(panel);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createTitlePanel() {
        JPanel panel = new JPanel();

        JLabel titleLabel = new JLabel("Title");
        panel.add(titleLabel);

        return panel;
    }

    private JPanel createDropDownPanel() {
        JPanel panel = new JPanel();

        DefaultComboBoxModel<String> model1 = new DefaultComboBoxModel<String>();
        model1.addElement("Selection 1");
        model1.addElement("Selection 2");
        model1.addElement("Selection 3");
        model1.addElement("Selection 4");

        JComboBox<String> comboBox1 = new JComboBox<String>(model1);
        panel.add(comboBox1);

        DefaultComboBoxModel<String> model2 = new DefaultComboBoxModel<String>();
        model2.addElement("Choice 1");
        model2.addElement("Choice 2");
        model2.addElement("Choice 3");
        model2.addElement("Choice 4");

        JComboBox<String> comboBox2 = new JComboBox<String>(model2);
        panel.add(comboBox2);

        return panel;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM