0
我想使JTable中的一個單元成爲JComboBox對象並能夠使用它。它必須只有一個單元格,而不是整個列。該表可以包含特定的單元格,但並非總是如此,其放置位置不是靜態的。我的問題在於把JComboBox放入可以使用的JTable中。我附上了我迄今能夠做到的代碼。表包含JComboBox,但是當我點擊它時,沒有列表並打開單元格的編輯器。我想讓名單出現。我應該做什麼或者應該在代碼中添加/修改什麼來實現我的目標?把JComboBox放到JTable中,並從列表中獲取元素而不是編輯單元格
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
public class CustomCellRenderer {
JTable table;
TableColumn tcol;
public static void main(String[] args) {
new CustomCellRenderer();
}
public CustomCellRenderer() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
Object data[][] = { { "Vinod", "Computer", "3" },
{ "Rahul", "History", "2" }, { "Manoj", "Biology", "4" },
{ "Sanjay", "PSD", "5" } };
String col[] = { "Name", "Course", "Year" };
DefaultTableModel model = new DefaultTableModel(data, col);
table = new JTable(model);
tcol = table.getColumnModel().getColumn(0);
tcol.setCellRenderer(new CustomTableCellRenderer());
tcol = table.getColumnModel().getColumn(1);
tcol.setCellRenderer(new CustomTableCellRenderer());
tcol = table.getColumnModel().getColumn(2);
tcol.setCellRenderer(new CustomTableCellRenderer());
JTableHeader header = table.getTableHeader();
JScrollPane pane = new JScrollPane(table);
panel.add(pane);
frame.add(panel);
frame.setSize(500, 150);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public class CustomTableCellRenderer extends DefaultTableCellRenderer implements ActionListener {
public Component getTableCellRendererComponent(JTable table,
Object obj, boolean isSelected, boolean hasFocus, int row,
int column) {
Component cell = super.getTableCellRendererComponent(table, obj,
isSelected, hasFocus, row, column);
if (((String) obj).equals("History")) {
JComboBox comboBox = new JComboBox();
comboBox.addItem("History");
comboBox.addItem("English");
comboBox.addItem("Biology");
comboBox.addItem("PE");
comboBox.addItem("None of the above");
comboBox.addActionListener(this);
return comboBox;
}
return cell;
}
public void actionPerformed(ActionEvent e) {
System.out.println("Perform some action");
}
}
}
謝謝,我剛剛找到這個例子,並想在這裏告知。 – dawrutowicz
你受歡迎。如果這個答案解決了你的問題,接受它。 – gontard