为什么jcombobox不可见?

时间:2013-10-08 04:30:43

标签: java swing

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


public class Dummy{
    String newSelection = null;

    public void init(){
        JFrame jFrame = new JFrame("Something");
        jFrame.setVisible(true);
        jFrame.setSize(new Dimension(600, 600));
        jFrame.setLayout(null);
        jFrame.setBackground(Color.BLACK);

        final String[] possibleNoOfPlayers = {"Two","Three"};

        final JComboBox comboBox = new JComboBox(possibleNoOfPlayers);
        newSelection = possibleNoOfPlayers[0];
        comboBox.setPreferredSize(new Dimension(200,130));
        comboBox.setLocation(new Point(200,200));
        comboBox.setEditable(true);
        comboBox.setSelectedIndex(0);
        comboBox.setVisible(true);
        comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                JComboBox box = (JComboBox) actionEvent.getSource();
                newSelection = (String) box.getSelectedItem();
                System.out.println(newSelection);
            }
        });
        jFrame.add(comboBox);
    }
}

我正在尝试向框架添加组合框。但它不可见。如果您点击该位置,它将显示选项。但它不可见。如果我遗漏了一些内容,请告诉我。

2 个答案:

答案 0 :(得分:4)

三件事......

  1. 您在添加之前已在您的框架上调用了setVisible
  2. 您正在使用null布局
  3. 您没有为comobox设置大小,这意味着它将(有效地)呈现为0x0大小。 (ps- setPreferredSize没有做你认为应该做的事情......)
  4. 建议的解决方案......

    最后调用setVisible并使用适当的布局管理器

答案 1 :(得分:1)

使用这个......

package oops;

import java.awt.BorderLayout;

public class jframe extends JFrame {

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                jframe frame = new jframe();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public jframe() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JComboBox comboBox = new JComboBox();
    comboBox.setBounds(159, 81, 189, 41);
    contentPane.add(comboBox);
}
}
相关问题