我尝试使用以下代码:
public class JComboBoxDemo extends JFrame{
private JPanel panelParents;
private JLabel lblTitle;
private JComboBox cboLanguage;
public JComboBoxDemo() {
super("JComboBox Demo");
setContentPane(panelParents);
String language[] = {"English","Khmer","Korea","Chinese","Thai","Russia"};
cboLanguage = new JComboBox(language);
cboLanguage.setSelectedIndex(1);
cboLanguage.setMaximumRowCount(5);
pack();
setBounds(100,100,450,256);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
}
但它在JComboBox
中没有显示任何内容,我的代码有什么问题?
答案 0 :(得分:1)
问题是您正在将null
传递给setContentPane
。下面的代码正在运行
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JComboBoxDemo1 extends JFrame {
private JPanel panelParents;
private JLabel lblTitle;
private JComboBox cboLanguage;
public JComboBoxDemo1() {
super("JComboBox Demo");
String language[] = {"English", "Khmer", "Korea", "Chinese", "Thai",
"Russia"};
cboLanguage = new JComboBox(language);
cboLanguage.setSelectedIndex(1);
cboLanguage.setMaximumRowCount(5);
getContentPane().add(cboLanguage);
pack();
setBounds(100, 100, 450, 256);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JComboBoxDemo1();
}
}
答案 1 :(得分:1)
以下是第二种方法。理想情况下,如果不扩展它的功能,则不应覆盖类。 首选合成而不是继承 ,详情为here。可以找到JFrame
个详细信息here
以下代码:
import java.awt.Component;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JComboBoxDemo {
private JPanel panelParents;
private JLabel lblTitle;
public JComboBoxDemo() {
JFrame frame = new JFrame("JComboBox Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(getMainComponent());
frame.pack();
frame.setBounds(100, 100, 450, 256);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
private Component getMainComponent() {
JComboBox cboLanguage = new JComboBox();
String language[] = {"English", "Khmer", "Korea", "Chinese", "Thai",
"Russia"};
cboLanguage = new JComboBox(language);
cboLanguage.setSelectedIndex(1);
cboLanguage.setMaximumRowCount(5);
return cboLanguage;
}
public static void main(String[] args) {
new JComboBoxDemo();
}
}