Java – jcombobox in JTable cell
•
Java
I have a JTable created using a model, which is based on an object matrix
for(int i=0; i < n ; i++) {
.....
data[i][5] = new JCombo@R_789_2419@(aux); // aux is a Vector of elements I wanna insert
}
table.setModel(new MyTableModel()); // MyTableModel() already takes into consideration the data[][] object
The problem is data [i] [5] = New JCombo@R_789_2419 @(aux); Will not be created in a specific cell of the JTable JCombo@R_789_2419 @Instead, paste the code into the line What can I do to solve this problem?
thank you.
Solution
One way is to override the getcelleditor () method to return the appropriate editor Here is an example to get you started:
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.*;
public class TableCombo@R_789_2419@ByRow extends JFrame
{
List<TableCellEditor> editors = new ArrayList<TableCellEditor>(3);
public TableCombo@R_789_2419@ByRow()
{
// Create the editors to be used for each row
String[] items1 = { "Red","Blue","Green" };
JCombo@R_789_2419@ combo@R_789_2419@1 = new JCombo@R_789_2419@( items1 );
DefaultCellEditor dce1 = new DefaultCellEditor( combo@R_789_2419@1 );
editors.add( dce1 );
String[] items2 = { "Circle","Square","Triangle" };
JCombo@R_789_2419@ combo@R_789_2419@2 = new JCombo@R_789_2419@( items2 );
DefaultCellEditor dce2 = new DefaultCellEditor( combo@R_789_2419@2 );
editors.add( dce2 );
String[] items3 = { "Apple","Orange","Banana" };
JCombo@R_789_2419@ combo@R_789_2419@3 = new JCombo@R_789_2419@( items3 );
DefaultCellEditor dce3 = new DefaultCellEditor( combo@R_789_2419@3 );
editors.add( dce3 );
// Create the table with default data
Object[][] data =
{
{"Color","Red"},{"Shape","Square"},{"Fruit","Banana"},{"Plain","Text"}
};
String[] columnNames = {"Type","Value"};
DefaultTableModel model = new DefaultTableModel(data,columnNames);
JTable table = new JTable(model)
{
// Determine editor to be used by row
public TableCellEditor getCellEditor(int row,int column)
{
int modelColumn = convertColumnIndexToModel( column );
if (modelColumn == 1 && row < 3)
return editors.get(row);
else
return super.getCellEditor(row,column);
}
};
System.out.println(table.getCellEditor());
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
}
public static void main(String[] args)
{
TableCombo@R_789_2419@ByRow frame = new TableCombo@R_789_2419@ByRow();
frame.setDefaultCloSEOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
Edit: update the code to use the suggestion of trashgod
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
