java - Java Swing 应用程序试图在按钮单击时填充 JComboBox
问题描述
我正在学习 Java Swing。我正在尝试开发作为学习目的的简单应用程序。以下代码存在多个问题。我尝试读取 csv 文件并在单击按钮时填充 JComboBox。
public class MyForm {
private JButton btnRead;
private JButton btnRead2;
private JComboBox cbCodes;
private JPanel mainPanel;
private DefaultComboBoxModel comboBoxModel;
public MyForm(){
// issue 1: I always get null pointer exception in this line
comboBoxModel = new DefaultComboBoxModel();
cbCodes = new JComboBox(comboBoxModel);
btnRead.addActionListener( e -> {
List<String[]> data = readData();
comboBoxModel.removeAllElements();
data.forEach(item -> comboBoxModel.addElement(item));
});
// issue 2: Since DefaultComboBoxModel was not working. I tried without it. As this I get correct data in the array. But when I make JComboBox with array. Nothing is filled. It is empty.
btnRead2.addActionListener( e -> {
List<String[]> data = readData();
String[] array = new String[data.size()];
data.toArray(array);
cbCodes = new JComboBox(array);
});
}
// issue 3: I can't complie the code without this empty method. Why do I need it?
// error: Form contains components with Custom Create option but no createUIComponents() method
void createUIComponents(){
}
public List<String[]> readData() {
String file = "data.csv";
List<String[]> content = new ArrayList<>();
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = "";
while ((line = br.readLine()) != null) {
if(line.contains("\"")){
content.add(line.split(" "));
}
content.add(line.split(","));
}
} catch (FileNotFoundException e) {
//Some error logging
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
public static void main(String[] args) {
JFrame frame = new JFrame("MyForm");
frame.setContentPane(new MyForm().mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
我在源代码中提出了我的问题,并附有评论,以便在此处准确显示这些问题所涉及的问题。
解决方案
您没有在您指示的行中获得 NullPointerException,而是在该行中,
btnRead.addActionListener( e -> {
因为 btnRead 尚未初始化!当您创建一个新的 JComboBox 时,您也必须将它添加到面板中。只是用new创建它不会显示它。但其背后的真正问题是:您使用错误的模型。写
comboBoxModel.removeAllElements(); for (final String string : array) { comboBoxModel.addElement(string); }
解决这个问题。
- 您在这里遇到的问题不在于您提供的代码,而是来自另一个组件。在某些时候,有人使用了 UI 设计师。那些设计者通常会创建初始化方法,就像createUIComponents一样。查看调用该方法的位置。
概要:
- 总而言之,你的代码真的很混乱。从新进行重组,这样会清理很多问题。
-
- 并尽快初始化 UI 组件,最好在声明行中进行:
private final JButton btnRead = new JButton("Read!");
- 并尽快初始化 UI 组件,最好在声明行中进行:
- 我强烈建议使用 Eclipse 或 IntelliJ 之类的 IDE,这将帮助您编写干净的代码并更轻松地查看和纠正问题。
推荐阅读
- javascript - How to prevent duplicate rows from being displayed in html?
- sql - Oracle SQL:使用 to_date 时输出错误的年份
- python - Keras 中 Adadelta 优化器中的学习率参数是什么?
- python - Pyttsx 未在 Windows 10 上显示已安装的语言
- kubernetes - 获取 PreStop 生命周期钩子执行结果
- php - 如何获得通过 SMTP 协议发送电子邮件的结果?
- android - 焦点不会自动转移到下一个edittext?
- javascript - 如何在车把文件中打印“body”元素?
- python - 如何打印数字列表及其平均值?
- html - 如何在相对 div 中包含固定栏并完美显示滚动条