I am a beginner in Java Programming. I want to use a JComboBox as a cell editor in a JTable. But I want to set the selected index of JCombobox on the value which is the current value of the cell when it is clicked to get edited. How I can do this?
我是Java编程的初学者。我想使用JComboBox作为JTable中的单元格编辑器。但我想在JCombobox的选定索引上设置值,该值是单击单元格进行编辑时单元格的当前值。我怎么能这样做?
the Class which I used for the cell and also for the items of Jcombobox:
我用于细胞的类和Jcombobox的项目:
public class PersianLetterIDPair {
private int id;
private String letter;
public PersianLetterIDPair(int id, String description)
{
this.id = id;
this.letter = description;
}
public int getID()
{
return id;
}
public String getLetter()
{
return letter;
}
public void setID(int inID)
{
id = inID;
}
public void setLetter(String inLetter)
{
letter = inLetter;
}
public String toString()
{
return letter;
}
}
}
the way I filled my Jcombobox:
我填充我的Jcombobox的方式:
Vector<PersianLetterIDPair> model2 = new Vector<PersianLetterIDPair>();
model1 = myDBLayer
.getVectorPersianLettersIDContent();
int tPLID;
String tPL;
Iterator iterator = model1.iterator();
while (iterator.hasNext()) {
Vector newRow = new Vector();
newRow = (Vector) iterator.next();
tPLID = (Integer) newRow.get(0);
tPL = (String) newRow.get(1);
model2.addElement(new PersianLetterIDPair(tPLID,
tPL));
}
PersianLetters0001 = new JComboBox(model2);
jTable2.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(PersianLetters0001));
I used a table model for my Jtable as follow:
我用Jtable的表模型如下:
public class FormSimilaritiesTableModel extends AbstractTableModel {
private DBLayer myDBLayer = new DBLayer();
private ResultSet rs;
private String colNames[];
private Vector<FormSimilarityRow> allRows;
private FormSimilarityRow row;
private Vector<FormSimilarityRow> newRow;
private int li_cols;
private String tableName;
private ResultSetMetaData myM;
private Vector<FormSimilarityRow> deletedKeys;
private Vector newRows;
private Vector updatedRows;
private boolean ibRowInserted = false;
private guiBaseTables myGuiBaseTables ;
boolean ibRowNew = false;
FormSimilaritiesTableModel() {
deletedKeys = new Vector();
newRows = new Vector();
updatedRows = new Vector();
try {
ResultSet rs = myDBLayer.getrsFormSimilarities();
li_cols = 3 ;
colNames = new String[li_cols];
colNames[0] = "Persian Letter 1";
colNames[1] = "Persian Letter 2";
colNames[2] = "Form Similarity";
allRows = new Vector<FormSimilarityRow>();
int rPLID1;
String rPL1;
int rPLID2;
String rPL2;
while (rs.next()) {
///newRow = new Vector();
rPLID1 = (Integer) rs.getObject(1);
rPL1 = (String) rs.getObject(2);
rPLID2 = (Integer) rs.getObject(3);
rPL2 = (String) rs.getObject(4);
allRows.addElement(new FormSimilarityRow(new PersianLetterIDPair(rPLID1, rPL1),new PersianLetterIDPair(rPLID2, rPL2), (Integer)rs.getObject(5)));
} // while
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public Class getColumnClass(int col) {
if (col == 0 || col == 1) {
return PersianLetterIDPair.class;
} else if (col == 2) {
return Integer.class;
} else {
return null;
}
}
public String getColumnName(int col) {
return colNames[col];
}
public int getColumnCount() {
return li_cols;
}
public int getRowCount() {
return allRows.size();
}
public Object getValueAt(int arow, int col) {
row = allRows.elementAt(arow);
if(col == 0){
PersianLetterIDPair pL1 = row.getPL1();
return pL1.getLetter();
}
else
if(col == 1){
PersianLetterIDPair pL2 = row.getPL2();
return pL2.getLetter();
}
else{
return row.getFS();
}
}
public boolean isCellEditable(int row, int col) {
int totalNewRows;
if (col == 0 || col == 1) {
totalNewRows = newRows.size();
for(int j = 0; j< totalNewRows; j++)
{
int rVal = ((Integer) newRows.get(j)).intValue();
if( rVal == row + 1){
return true;
}
}
return false;
} else {
return true;
}
}
public void setValueAt(Object aValue, int aRow, int aCol) {
FormSimilarityRow dataRow = allRows.elementAt(aRow);
if (aCol == 0){
PersianLetterIDPair sV = (PersianLetterIDPair) aValue;
dataRow.setPL1(sV);
}
else
if (aCol == 1){
PersianLetterIDPair sV = (PersianLetterIDPair) aValue;
dataRow.setPL2(sV);
}
else
dataRow.setFS((Integer) aValue);
fireTableCellUpdated(aRow, aCol);
}
...
}
}
and definition of my Jtable is as:
我的Jtable的定义如下:
myFormSimilaritiesTableModel = new FormSimilaritiesTableModel();
jTable2 = new JTable();
jScrollPane2.setViewportView(jTable2);
jTable2.setModel(myFormSimilaritiesTableModel);
jTable2.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jTable2.getTableHeader()
.setReorderingAllowed(false);
I changed the getValueAt method following the tip which was said by @Polet to return the PersianLetterIDPair:
我更改了@Polet所说的提示后面的getValueAt方法,以返回PersianLetterIDPair:
public Object getValueAt(int arow, int col) {
row = allRows.elementAt(arow);
if(col == 0){
PersianLetterIDPair pL1 = row.getPL1();
//return pL1.getLetter();
return pL1;
}
else
if(col == 1){
PersianLetterIDPair pL2 = row.getPL2();
//return pL2.getLetter();
return pL2;
}
else{
return row.getFS();
}
}
Then I create a TableCellRenderer:
然后我创建一个TableCellRenderer:
class PersianLetterIDPairRenderer extends DefaultTableCellRenderer
{
{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setText(((PersianLetterIDPair)value).getLetter());
return this;
}
}
}
Then I add to my Jtable:
然后我添加到我的Jtable:
TableColumn tCol = jTable2.getColumnModel().getColumn(0);
tCol.setCellRenderer(new PersianLetterIDPairRenderer());
tCol = jTable2.getColumnModel().getColumn(1);
tCol.setCellRenderer(new PersianLetterIDPairRenderer());
But it gets correct when I disconnected from the TableCellRenderer as:
但是当我从TableCellRenderer断开连接时,它变得正确:
TableColumn tCol = jTable2.getColumnModel().getColumn(0);
//tCol.setCellRenderer(new PersianLetterIDPairRenderer());
tCol = jTable2.getColumnModel().getColumn(1);
//tCol.setCellRenderer(new PersianLetterIDPairRenderer());
2 个解决方案
#1
1
Check out This link Click here
看看这个链接点击这里
OR
要么
See this little example :
看到这个小例子:
import javax.swing.*;
import java.awt.*;
import javax.swing.table.TableColumn;
public class TableTest extends JFrame {
JTable table ;
public TableTest(){
table = new JTable(4,2);
String []subject = {"Java Programming","Hoshang","Mathematics","Database"};
String []lecturer={"Nuhara","Jon","Saran","Mikey"};
table.setSize(200, 200);
JComboBox subj = new JComboBox(subject);
JComboBox lec = new JComboBox(lecturer);
table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(lec));
table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(subj));
/*
* OR you can use TableColumn
*
*/
// TableColumn tc = table.getColumnModel().getColumn(0);
// tc.setCellEditor(new DefaultCellEditor(subj));
this.add(new JScrollPane(table),BorderLayout.CENTER);
this.setVisible(true);
this.setSize(300,200);
this.setDefaultCloseOperation(3);
}
public static void main(String...ag){
new TableTest();
}
}
#2
1
As suggested, use the DefaultCellEditor
with a JComboBox
.
如建议的那样,将DefaultCellEditor与JComboBox一起使用。
Small working example demonstrating this:
小工作示例证明了这一点:
import java.awt.BorderLayout;
import java.util.Random;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TestTable2 {
protected void initUI() {
DefaultTableModel model = new DefaultTableModel();
for (int i = 0; i < 3; i++) {
model.addColumn("Col-" + (i + 1));
}
Random random = new Random();
for (int i = 0; i < 2000; i++) {
Vector<Object> row = new Vector<Object>();
for (int j = 0; j < 3; j++) {
row.add(VALUES[random.nextInt(VALUES.length)]);
}
model.addRow(row);
}
JTable table = new JTable(model);
DefaultCellEditor editor = new DefaultCellEditor(new JComboBox(VALUES));
for (int i = 0; i < table.getColumnCount(); i++) {
table.getColumnModel().getColumn(i).setCellEditor(editor);
}
JFrame frame = new JFrame(TestTable2.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollpane = new JScrollPane(table);
frame.add(scrollpane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestTable2().initUI();
}
});
}
private static final String[] VALUES = { "Sun", "Hello", "Sky", "Cloud", "World", "Time", "System", "Computer", "Dummy", "Simple",
"Today", "Lorem" };
}
#1
1
Check out This link Click here
看看这个链接点击这里
OR
要么
See this little example :
看到这个小例子:
import javax.swing.*;
import java.awt.*;
import javax.swing.table.TableColumn;
public class TableTest extends JFrame {
JTable table ;
public TableTest(){
table = new JTable(4,2);
String []subject = {"Java Programming","Hoshang","Mathematics","Database"};
String []lecturer={"Nuhara","Jon","Saran","Mikey"};
table.setSize(200, 200);
JComboBox subj = new JComboBox(subject);
JComboBox lec = new JComboBox(lecturer);
table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(lec));
table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(subj));
/*
* OR you can use TableColumn
*
*/
// TableColumn tc = table.getColumnModel().getColumn(0);
// tc.setCellEditor(new DefaultCellEditor(subj));
this.add(new JScrollPane(table),BorderLayout.CENTER);
this.setVisible(true);
this.setSize(300,200);
this.setDefaultCloseOperation(3);
}
public static void main(String...ag){
new TableTest();
}
}
#2
1
As suggested, use the DefaultCellEditor
with a JComboBox
.
如建议的那样,将DefaultCellEditor与JComboBox一起使用。
Small working example demonstrating this:
小工作示例证明了这一点:
import java.awt.BorderLayout;
import java.util.Random;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TestTable2 {
protected void initUI() {
DefaultTableModel model = new DefaultTableModel();
for (int i = 0; i < 3; i++) {
model.addColumn("Col-" + (i + 1));
}
Random random = new Random();
for (int i = 0; i < 2000; i++) {
Vector<Object> row = new Vector<Object>();
for (int j = 0; j < 3; j++) {
row.add(VALUES[random.nextInt(VALUES.length)]);
}
model.addRow(row);
}
JTable table = new JTable(model);
DefaultCellEditor editor = new DefaultCellEditor(new JComboBox(VALUES));
for (int i = 0; i < table.getColumnCount(); i++) {
table.getColumnModel().getColumn(i).setCellEditor(editor);
}
JFrame frame = new JFrame(TestTable2.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollpane = new JScrollPane(table);
frame.add(scrollpane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestTable2().initUI();
}
});
}
private static final String[] VALUES = { "Sun", "Hello", "Sky", "Cloud", "World", "Time", "System", "Computer", "Dummy", "Simple",
"Today", "Lorem" };
}