2
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);
    }
}

我正在尝试将组合框添加到框架中。但它不可见。如果您单击该位置,它将显示选项。但它不可见。如果我遗漏了什么,请告诉我。

4

2 回答 2

4

三件事...

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

建议的解决方案...

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

于 2013-10-08T04:33:28.353 回答
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);
}
}
于 2013-10-08T04:36:01.840 回答