如何将jTextfield中的数据添加到jTable中?我不知道为什么我失败了。请看一下

时间:2018-01-12 07:58:36

标签: java netbeans jframe

所以我跟着一个在youtube上制作杂货收银机的视频。我小心翼翼地一步一步地跟着它。但当谈到getText进入jTable1行时,就像,当我按下jButton1时,它不会像视频所示那样起作用。

所以,我把这个脚本复制到我的项目中,绝望地看它是否有效,但它没有。然后,当我在原始项目的原始文件上尝试它。有用。所以试着复制所有这些。完整到我的项目。编码,变量,已声明的按钮或用英语调用的按钮没有区别。 仍然不起作用。

 /*
 * To change this license header, choose License Headers in Project 
 Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package kasiraldo;
 import static java.awt.event.KeyEvent.VK_BACK_SPACE;
 import java.util.Vector;
 import javax.swing.table.DefaultTableModel;
//import javax.swing.JTable;
/**
*
* @author AldoFerino
*/
public class kasirJframe extends javax.swing.JFrame {

/**
 * Creates new form kasirJframe
 */
public kasirJframe() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    Nama = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    Harga = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    Qty = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    Jumlah = new javax.swing.JLabel();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    Pesan = new javax.swing.JLabel();
    Totalharga = new javax.swing.JLabel();
    Bayar = new javax.swing.JTextField();
    jButton3 = new javax.swing.JButton();
    Kembalian = new javax.swing.JLabel();
    jButton2 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("Nama");

    Nama.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            NamaActionPerformed(evt);
        }
    });

    jLabel2.setText("Harga");

    Harga.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            HargaActionPerformed(evt);
        }
    });
    Harga.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            HargaKeyPressed(evt);
        }
        public void keyTyped(java.awt.event.KeyEvent evt) {
            HargaKeyTyped(evt);
        }
    });

    jLabel3.setText("Qty");

    Qty.setText(" ");
    Qty.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            QtyActionPerformed(evt);
        }
    });
    Qty.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            QtyKeyPressed(evt);
        }
        public void keyTyped(java.awt.event.KeyEvent evt) {
            QtyKeyTyped(evt);
        }
    });

    jButton1.setText("Input");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    Jumlah.setText("0");

    jTable1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {

        },
        new String [] {
            "Nama", "Harga", "Qty", "Jumlah"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, false, false, false
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    jTable1.setAutoscrolls(false);
    jTable1.setColumnSelectionAllowed(true);
    jTable1.setOpaque(false);
    jScrollPane2.setViewportView(jTable1);
    jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    Pesan.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

    Totalharga.setText("Rp.");

    Bayar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            BayarActionPerformed(evt);
        }
    });
    Bayar.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            BayarKeyPressed(evt);
        }
        public void keyTyped(java.awt.event.KeyEvent evt) {
            BayarKeyTyped(evt);
        }
    });

    jButton3.setText("Bayar");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    Kembalian.setText("Rp.");

    jButton2.setText("Delete");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(61, 61, 61)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING))
                        .addComponent(jLabel1))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(Nama)
                        .addComponent(Harga, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(Qty, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jButton1)
                            .addGap(28, 28, 28)
                            .addComponent(jButton2))
                        .addComponent(Jumlah, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(Kembalian, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(Bayar, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(Totalharga, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(Pesan, javax.swing.GroupLayout.PREFERRED_SIZE, 365, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(30, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(Nama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(10, 10, 10)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(Harga, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addComponent(Jumlah, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel3)
                .addComponent(Qty, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton1)
                .addComponent(jButton2))
            .addGap(27, 27, 27)
            .addComponent(Pesan, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(Totalharga, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(Bayar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton3)
            .addGap(11, 11, 11)
            .addComponent(Kembalian, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(12, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
    setLocationRelativeTo(null);
}// </editor-fold>                        

private void BayarActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
}                                     

private void NamaActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
}                                    

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // Tombol Input untuk masukkan data yang di input oleh user ke tabel
    Pesan.setText("");
    DefaultTableModel a = (DefaultTableModel) jTable1.getModel();
    if(Nama.getText().trim().equals("")){
        Pesan.setText("MAAF, NAMA BARANG HARUS DI ISI");
    }else{
        int c = Integer.parseInt(Harga.getText());
        int b = Integer.parseInt(Qty.getText());
        int d = b * c;
        Jumlah.setText(""+d);
        Jumlah.setVisible(false);
        int t = 0;
        Vector z = new Vector();
        z.add(Nama.getText());
        z.add("Rp.".concat(Harga.getText()));
        z.add(Qty.getText());
        z.add("Rp.".concat(Jumlah.getText()));
        a.addRow(z);
        for(int e = 0; e <a.getRowCount(); e++){
            t += Integer.parseInt(a.getValueAt(e, 3).toString().substring(3));
        }
        Totalharga.setText("Rp."+t);
        Nama.setText("");
        Harga.setText("");
        Qty.setText("");
    }
}                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // Hapus
    //DefaultTableModel a = (DefaultTableModel) jTable1.getModel();
    DefaultTableModel a = (DefaultTableModel) jTable1.getModel();
    int select = jTable1.getSelectedRow();
    a.removeRow(select);
    Nama.setText("");
    Harga.setText("");
    Qty.setText("");
    int t= 0;
    for(int e = 0; e <a.getRowCount(); e++){
        t += Integer.parseInt(a.getValueAt(e, 3).toString().substring(3));
    }
    Totalharga.setText("Rp."+t);
    int g = Integer.parseInt(Totalharga.getText().substring(3));
    int f = Integer.parseInt(Bayar.getText());
    int h = f - g;
    Kembalian.setText("Rp."+h);
}                                        

private void BayarKeyTyped(java.awt.event.KeyEvent evt) {                               
    // tertekan di kolom bayar
    Pesan.setText("");
    char a = evt.getKeyChar();
    int  b = evt.getKeyCode() ;
    if(!Character.isDigit(a)){
        evt.consume();
        Pesan.setText("maaf hanya bisa input pakai angka");
    } else if (b == VK_BACK_SPACE) {
        evt.consume();
        Pesan.setText("maaf hanya bisa input pakai angka");
    }
}                              

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    int g = Integer.parseInt(Totalharga.getText().substring(3));
    int f = Integer.parseInt(Bayar.getText());
    int h = f - g;
    Kembalian.setText("Rp."+h);
}                                        

private void QtyKeyTyped(java.awt.event.KeyEvent evt) {                             
    // Qty terketik
    Pesan.setText("");
    char a = evt.getKeyChar();
    int  b = evt.getKeyCode() ;
    if(!Character.isDigit(a)){
        evt.consume();
        Pesan.setText("maaf hanya bisa input pakai angka");
    } else if (b == VK_BACK_SPACE) {
        evt.consume();
        Pesan.setText("maaf hanya bisa input pakai angka");
    }
}                            

private void HargaKeyTyped(java.awt.event.KeyEvent evt) {                               
    // TODO add your handling code here:
    Pesan.setText("");
    char a = evt.getKeyChar();
    int  b = evt.getKeyCode() ;
    if(!Character.isDigit(a)){
        evt.consume();
        Pesan.setText("maaf hanya bisa input pakai angka");
    } else if (b == VK_BACK_SPACE) {
        evt.consume();
        Pesan.setText("maaf hanya bisa input pakai angka");
    }
}                              

private void BayarKeyPressed(java.awt.event.KeyEvent evt) {                                 
    // TODO add your handling code here:
}                                

private void HargaActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
}                                     

private void HargaKeyPressed(java.awt.event.KeyEvent evt) {                                 
    // TODO add your handling code here:
}                                

private void QtyKeyPressed(java.awt.event.KeyEvent evt) {                               
    // TODO add your handling code here:
}                              

private void QtyActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
}                                   

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(kasirJframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new kasirJframe().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JTextField Bayar;
private javax.swing.JTextField Harga;
private javax.swing.JLabel Jumlah;
private javax.swing.JLabel Kembalian;
private javax.swing.JTextField Nama;
private javax.swing.JLabel Pesan;
private javax.swing.JTextField Qty;
private javax.swing.JLabel Totalharga;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
// End of variables declaration                   
void isVisible(boolean b) {
    throw new UnsupportedOperationException("Not supported yet."); //To 
change body of generated methods, choose Tools | Templates.
}
}

当我在用户界面窗口或jframe或设计中按下jButton1或按钮“Input”时,在输出窗口选项卡中给出了这个错误。

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: " 1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at kasiraldo.kasirJframe.jButton1ActionPerformed(kasirJframe.java:264)
at kasiraldo.kasirJframe.access$700(kasirJframe.java:15)
at kasiraldo.kasirJframe$6.actionPerformed(kasirJframe.java:97)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD SUCCESSFUL (total time: 9 seconds)

对不起,如果我的问题看起来很模糊......

2 个答案:

答案 0 :(得分:1)

您已将Qty文本字段的默认值设置为" "(一个空格)。

Qty.setText(" ");

您可能会在该文本字段中添加1并按下提交按钮以触发jButton1ActionPerformed方法。您正在尝试将文本" 1"解析为导致java.lang.NumberFormatException: For input string: " 1"异常的整数 -

int b = Integer.parseInt(Qty.getText());

简单的解决方案会将""(空白)设置为Qty文本字段 -

Qty.setText("");

它应该可以正常工作。

答案 1 :(得分:0)

java.lang.NumberFormatException: For input string: " 1"

实际上,这说明了一切:"1"可以解析为数字,但添加了空格" 1",这是纯文本String,而不是数字格式化了。

在您要解析的trim()上调用String,以删除前导和尾随空格。