Search code examples
javaswingjtablejcombobox

How to update the cells of a table from a combobox?


enter image description here

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import net.java.dev.designgridlayout.DesignGridLayout;
import java.io.*;
import net.java.dev.designgridlayout.Tag;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;  
import java.sql.*;

class table1
{
JFrame JF;
Container C;
JPanel JP;
JLabel creditLabel;
JComboBox credit;
String[] Credit = {"Vasan Phalke", "Pansare", "Anil Kg", "Suresh"};
String[] Names = {"Name", "Qty", "Rate/ Kg", "Rate/Dzn.", "Total Amt."};
JTable table;
DefaultTableModel model;
JScrollPane scrollPane;

public table1()
{
JF = new JFrame();
JP = new JPanel();
C= JF.getContentPane();
JF.pack();
JF.setLocationRelativeTo(null); 
JF.setVisible(true);    

DesignGridLayout layout = new DesignGridLayout(C);

creditLabel = new JLabel("Credit");
credit = new JComboBox<String>(Credit);
model = new DefaultTableModel(Names,5);
    table =new JTable(model){@Override
public boolean isCellEditable(int arg0, int arg1)
{
    return true;
}
               };


  scrollPane= new JScrollPane(table);

layout.row().grid(creditLabel).add(credit);
layout.emptyRow();
layout.row().grid().add(table);

C.add(JP);
}

public static void main(String args[])
{
new table1();
}
}

By clicking on the value of combobox, it should appear in the name column of the table, and what changes should be made to the table for automatic calculation, ie, when i enter qty and rate, total amount should automatically be calculated. How all these things can be done, please help. Thanks in advance.


Solution

  • Read the section from the Swing tutorial on How to Use Tables

    The tutorial shows you how to use a combo box as an editor for a column in a table. This is what you should be doing instead of having a separate combo box.

    To calculate the amount, you need to create a custom TableModel and override the setValueAt() method. Whenever the quantity or rate changes you recalculate the amount.