如何将组件分配给组合框

时间:2015-04-07 15:11:32

标签: java arrays swing jcombobox

为了使程序正常工作,我需要一个下拉菜单(组合框),显示转换为化学计量的所有可能单位。

我知道你必须为一个组合框分配一个数组,但我不知道如何。如果有人可以提供帮助,那就太好了。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Conversion extends JFrame
{
    private JLabel molarMass1;
    private JLabel molarMass2;
    private JLabel moles1;
    private JLabel moles2;
    private JLabel amount1;
    private JLabel amount2;

    private JTextField M1M2;
    private JTextField M2M1;
    private JTextField moles1moles2;
    private JTextField moles2moles1;
    private JTextField amount1amount2;
    private JTextField amount2amount1;
    private JComboBox UnitsOne;
    private JComboBox UnitsTwo;

    private static final int WIDTH = 500;
    private static final int HEIGHT = 50;





    Conversion()
    {}

    public void burst()
    {
        setTitle("Stoichiometry");
        Container z = getContentPane();
        z.setLayout(new GridLayout(1, 4));

        molarMass1 = new JLabel("Molar Mass 1: ", SwingConstants.LEFT);
        molarMass2 = new JLabel("Molar Mass 2: ", SwingConstants.RIGHT);
        moles1 = new JLabel("Number of Moles 1: ", SwingConstants.LEFT);
        moles2 = new JLabel("Number of Moles 2: ", SwingConstants.RIGHT);
        amount1 = new JLabel("Amount of substance 1: ", SwingConstants.LEFT);
        amount2 = new JLabel("Amount of substance 2: ", SwingConstants.RIGHT);

        M1M2 = new JTextField(7);
        M2M1 = new JTextField(7);
        moles1moles2 = new JTextField(6);
        moles2moles1 = new JTextField(6);
        amount1amount2 = new JTextField(5);
        amount2amount1 = new JTextField(5);
        UnitsOne = new JComboBox(10);
        UnitsTwo = new JComboBox(10);


        z.add(molarMass1);
        z.add(M1M2);
        z.add(molarMass2);
        z.add(M2M1);

        z.add(moles1);
        z.add(moles1moles2);
        z.add(moles2);
        z.add(moles2moles1);

        z.add(amount1);
        z.add(amount1amount2);
        z.add(amount2);
        z.add(amount2amount1);

        z.add(UnitsOne);
        z.add(UnitsTwo);


        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
}
}

1 个答案:

答案 0 :(得分:0)

我没有看到你想要分配给组合框的数组在你的代码中,但是有一个构造函数可以完全满足你的需要:http://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html#JComboBox(E[])

或者,您可以稍后使用addItem() method

将项目添加到JComboBox

另请看这里:https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html