Selasa, 28 April 2015

JAVA - How To Add A Row To JTable Using JOptionPane showInputDialog In Java NetBeans

JOptionPane.showInputDialog

How To Insert A Row To JTable Using JOptionPane.showInputDialog In Java

__________________________________________________________________________

In This Java Code We Will See How To Add A Row To JTable From JOptionPane showInputDialog In Java Programming Language.




Project Source Code:


package java_tutorials;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 * @author 1bestcsharp.blogspot.com
 */
public class Java_JTable_Add_Row_Using_JOptionPane extends javax.swing.JFrame {

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

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        Btn_Add_Row = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "First Name", "Last Name ", "Age"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        Btn_Add_Row.setText("Add Row");
        Btn_Add_Row.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Btn_Add_RowActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 410, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(134, 134, 134)
                        .addComponent(Btn_Add_Row, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(15, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addComponent(Btn_Add_Row)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(14, Short.MAX_VALUE))
        );

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

// button add row to jtable
    private void Btn_Add_RowActionPerformed(java.awt.event.ActionEvent evt)
 {                                            
        // get data from InputDialog
        String id = JOptionPane.showInputDialog("Enter The Id");
        String fname = JOptionPane.showInputDialog("Enter The First Name");
        String lname = JOptionPane.showInputDialog("Enter The Last Name");
        String age = JOptionPane.showInputDialog("Enter The Age");
        
        Object rowData[] = new Object[4];
        
        rowData[0] = id;
        rowData[1] = fname;
        rowData[2] = lname;
        rowData[3] = age;
        
        DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
        
        model.addRow(rowData);

    }                                           

    /**
     * @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 ex) {
            java.util.logging.Logger.getLogger(Java_JTable_Add_Row_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Java_JTable_Add_Row_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Java_JTable_Add_Row_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Java_JTable_Add_Row_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton Btn_Add_Row;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   
}

=> OutPut :
add row to jtable
Add Row To JTable Using showInputDialog


Another Project Source Code:

package javaapp;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class Woirk extends JFrame {

    Object[] columns = {"ID","First Name","Last Name","Age"};

    public Woirk(){

        super("JFrame Name");

        JTable table = new JTable();

        JScrollPane pane = new JScrollPane();

        JButton button = new JButton("Add Row");

        JPanel panel = new JPanel(new BorderLayout());

        DefaultTableModel model = (DefaultTableModel)table.getModel();

        model.setColumnIdentifiers(columns);


        pane.setViewportView(table);

        panel.add(pane,BorderLayout.NORTH);

        panel.add(button,BorderLayout.SOUTH);
        
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

             String id;
             String fn;
             String ln;
             String age;

             //get th id from the first InputDialog
             id = JOptionPane.showInputDialog("Enter Your ID");

             //get th first name from the second showInputDialog
             fn = JOptionPane.showInputDialog("Enter Your First Name");

             //................
             ln = JOptionPane.showInputDialog("Enter Your Last Name");

             //................
             age = JOptionPane.showInputDialog("Enter Your Age");
             
             //add the row to the model
             model.addRow(new Object[]{id,fn,ln,age});
            }
        });
        
        setContentPane(panel);

        setSize(800, 500);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setLocationRelativeTo(null);

        setVisible(true);
        
    }
    
    public static void main(String[] args){

         new Woirk();
    }
    
}

////////OUTPUT:
insert row to jtable
before button click
enter values to the show input dialog
after button click: enter data to the showInputDialog
row inserted
Now Your Can See Your Row In The JTable 



See: Update A JTable Row Using JOptionPane showInputDialog

Bagikan

Jangan lewatkan

JAVA - How To Add A Row To JTable Using JOptionPane showInputDialog In Java NetBeans
4/ 5
Oleh

Subscribe via email

Suka dengan artikel di atas? Tambahkan email Anda untuk berlangganan.