【问题标题】:how to get string from jtable with null cell如何从带有空单元格的jtable中获取字符串
【发布时间】:2016-05-25 04:14:18
【问题描述】:

我有 jtable 和来自 mysql 的数据。 在 mysql 中,我有一个允许为空的列(它称为“fil”)。 当我将数据检索到 jtable 时,就可以了。 然后,如果“fil”不为空,我想填充 jtextarea 并启用按钮,方法是单击 jtable 行。 这是我的代码:

private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
int row = jTable1.getSelectedRow();
String num = jTable1.getValueAt(row, 0).toString();
String sub = jTable1.getValueAt(row, 1).toString();
String desc = jTable1.getValueAt(row, 2).toString();
String start = jTable1.getValueAt(row, 3).toString();
String end = jTable1.getValueAt(row, 4).toString();
String sta = jTable1.getValueAt(row, 5).toString();
String fil = jTable1.getValueAt(row, 6).toString();
if (fil != "") {
  jButton1.setEnabled(true);
  jButton1.setToolTipText(fil);
} else {
  jButton1.setEnabled(false);
  jButton1.setToolTipText("");
}
jTextArea1.setText("Subject: " + sub + "\n" + "Description: " + "\n" + desc + "\n" + "From " + start + " to " + end + "\n" + "Status: " + sta);

jLabel3.setText(num);

问题是当我单击带有 null 'fil' 的行时,程序给出错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

【问题讨论】:

  • // TODO add your handling code here: 这对我们对问题的理解增加了nothing,因此是噪音。 1) 为了尽快获得更好的帮助,请发布minimal reproducible exampleShort, Self Contained, Correct Example。对源代码中的一些数据进行硬编码,以替换数据库。 2) 使用逻辑一致的缩进代码行和块的形式。缩进是为了让代码的流程更容易理解!
  • 您在哪一行收到此错误?
  • @YAS_Bangamuwage 在此代码中,在“String fil = jTable1.getValueAt(row, 6).toString();”行中

标签: java mysql swing jtable


【解决方案1】:
if (fil != "") {

应该是:

if (fil != null) {

编辑:

String fil = jTable1.getValueAt(row, 6).toString();

你不能在空对象上调用 toString() 所以你需要类似的东西:

Object filObject = jTable1.getValueAt(row, 6);
String fil = (filObject == null) ? "" : filObject.toString();

然后你会使用你原来的测试:

If (fil != "")

【讨论】:

  • 以后告诉我们导致 NPE 的语句。请参阅编辑以了解我的下一个猜测。如果它没有帮助,那么您已经被要求发布MCVE
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-29
  • 2021-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-14
  • 1970-01-01
相关资源
最近更新 更多