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);
}
}
我正在尝试向框架添加组合框。但它不可见。如果您点击该位置,它将显示选项。但它不可见。如果我遗漏了一些内容,请告诉我。
答案 0 :(得分:4)
三件事......
setVisible
null
布局0x0
大小。 (ps- setPreferredSize
没有做你认为应该做的事情......)建议的解决方案......
最后调用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);
}
}