Answer on Question#49033 - Programming – Java
Question: “how do i make a jcombobox affect two cell in a row of jtable in a java program”.
Answer:
You may do it like this:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTable;
class JCBaffect2cellOfJTable extends JFrame implements ActionListener{
public static void main(String[] args) {
new JCBaffect2cellOfJTable();//create the object of the class
//JCBaffect2cellOfJTable
}
JTable table;//declare the table
JComboBox<String> jcb;//declare the JComboBox object
JCBaffect2cellOfJTable(){//create the constructor
String[] callHeads = {"Column 1", "Column 2", "Column 3"};//initialize the column header
Object data[][] = {{"Cell 1", "Cell 2", "Cell 3"}};//initialize the data
table = new JTable(data, callHeads);//create the JTable object
JScrollPane jsp = new JScrollPane(table);//create the JScrollPane object and add the
//table
add(jsp);//add the JScrollPane to the frame
jcb = new JComboBox<>();//create the JComboBox object
jcb.addItem("Make a choice"); //add the choice item to the ComboBox
jcb.addItem("Affect"); //add the item to affect two cells of the row
jcb.addItem("Don't affect"); //add the item to do nothing
jcb.addActionListener(this); //registration for the ActionListener
add(jcb); //add the JComboBox to the frame
setLayout(new FlowLayout()); //set the layout manager for our frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //terminate the application when
//the window closes
pack(); //set the size of our frame
this.setVisible(true); //make visible our object JCBaffect2cellOfJTable
}
@Override
public void actionPerformed(ActionEvent e) {//method of ActionListener interface
//which we should to override
String s = (String)jcb.getSelectedItem(); //find out which item was chosen, cast
//the return value to the type of String and stored in the variable "s"
if (s.equals("Affect")){ //it was chosen item "Affect"
table.setValueAt("Changed", 0, 0); //set value "Changed" to the first cell
table.setValueAt("Changed", 0, 1); //set value "Changed" to the second
//cell
}
}
}That is, you should to use setValueAt () method for setting of changes in any of the cells.
http://www.AssignmentExpert.com/
Comments