You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java报错'void' type not allowed here的原因及解决方法

Java Swing 'void' type not allowed here 报错解决方案

报错根因

Swing中JTextField.setText()是无返回值(void)的方法,你在代码中直接将txtTotalBayar.setText(sum+"")的返回值作为Integer.parseInt()的入参,而void类型没有可被解析的内容,因此触发该报错。
此外这段逻辑本身存在冗余:你已经提前算出了总金额sum,完全不需要先把sum写到文本框,再从文本框读出来转成整数赋值给LN.Totalbayar,多步操作完全没有必要。

修正方案

将报错的那一行拆成两行即可:

// 先给文本框设置显示值
txtTotalBayar.setText(sum + "");
// 直接把已算出的sum赋值给Totalbayar属性,不需要重复做类型转换
LN.Totalbayar = sum;

完整修正后的btnProsesActionPerformed方法代码

private void btnProsesActionPerformed(java.awt.event.ActionEvent evt) {                                          
    ClassProgramTiket LN = new ClassProgramTiket();
    String hrTiket = txtHargaTiket.getText();
    String jmlTiket = txtJumlahTiket.getText();
    int harga = Integer.valueOf(hrTiket);
    int jumlah = Integer.valueOf(jmlTiket);
    int sum = harga * jumlah;    
    LN.Nama=txtNama.getText();
    LN.KodeKereta= (String)cbokodeKereta.getSelectedItem();
    LN.NamaKereta=(String)jenisKereta.getSelectedItem();
    LN.Jurusan= (String)jurusan.getSelectedItem();
    LN.JenisTiket= (String)jenisTiket.getSelectedItem();
    LN.HargaTiket= Integer.parseInt(txtHargaTiket.getText());
    LN.JumlahTiket= Integer.parseInt(txtJumlahTiket.getText());      
    // 修正后的代码
    txtTotalBayar.setText(sum + "");
    LN.Totalbayar = sum;
    Tiket.addElement(LN);
}  

内容的提问来源于stack exchange,提问作者adyt01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 05:36:07