JComboBox没有出现在窗口中

时间:2014-03-22 18:12:02

标签: java swing layout jcombobox

private String stringComboBoxElement[] = {"Roll", "SetCode", "Answers", "Others"};

contentPane = new JPanel();

contentPane.setLayout(null);

comboBoxfields = new JComboBox(stringComboBoxElement);

    comboBoxfields.setBounds(180, 50, 120, 30);
    comboBoxfields.setFont(new Font("sansserif", Font.TRUETYPE_FONT | Font.PLAIN, 15));
    comboBoxfields.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));

    if(stringComboBoxElement.length > 5)
        comboBoxfields.setMaximumRowCount(5);
    else
        comboBoxfields.setMaximumRowCount(stringComboBoxElement.length);

    comboBoxfields.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if(e.getStateChange() == ItemEvent.SELECTED)
                textFieldName.setText((String) e.getItem());
        }
    });
    contentPane.add(comboBoxfields);

我做了所有事情,但JComboBox没有出现在窗口中。有什么问题,我该如何解决?无法上传完整代码。问题出在这里,没有它一切正常。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:2)

以下代码适用于我:

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

public class Example {
    private static final String COMBO_BOX_ELEMENTS[] = {"Roll", "SetCode", "Answers", "Others"};

    public static void main(String[] args) {
      JFrame window = new JFrame("Example");

      JPanel contentPane = new JPanel();

      contentPane.setLayout(new GridBagLayout());

      final JComboBox comboBoxfields = new JComboBox(COMBO_BOX_ELEMENTS);

      comboBoxfields.setFont(new Font("sansserif", Font.TRUETYPE_FONT | Font.PLAIN, 15));
      comboBoxfields.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));

      comboBoxfields.setMaximumRowCount(5);

      comboBoxfields.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
                System.out.println(
                    "'"  + comboBoxfields.getSelectedItem().toString() + "'"
                    + " was selected");
          }
      });

      contentPane.add(comboBoxfields);

      window.add(contentPane); // I guess this is what you need to do.
      window.setSize(500, 500);
      window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      window.setVisible(true);
    }
}

如@nachokk所述,您需要将contentPane添加到JFrame