【发布时间】:2025-12-06 21:45:02
【问题描述】:
对于 Java Kepler Eclipse 和 Jtable,我正在尝试使其在选择特定表格单元格时,该单元格将用作 editorPane;或者让整个专栏作为 editorPane 工作。当我单击 COMMENTS 列上的单元格时,它会放大该行,但我无法将其用作 editorPane。我的项目实际上非常不同,但我用表格编写了这个迷你项目,因此您可以复制、粘贴和运行它,以便在单击 COMMENTS 单元格时准确查看问题所在。
我试图使该列成为一个 editorPane,就像我使用复选框使列 DONE 一样,但它不起作用或者我做错了。我也尝试过 cellRenderer,但我也无法做到。
无论是整列作为editorPane还是只作为选定的单元格都无关紧要,只要它更容易,只要它可以工作
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
public class JavaTestOne {
JFrame frmApp;
private JTable table;
private JCheckBox checkbox;
DefaultTableModel model;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JavaTestOne window = new JavaTestOne();
window.frmApp.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public JavaTestOne() {
initialize();
}
private void initialize() {
frmApp = new JFrame();
frmApp.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 13));
frmApp.setBounds(50, 10, 1050, 650);
frmApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmApp.getContentPane().setLayout(new CardLayout(0, 0));
frmApp.setTitle("App");
{
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(0, 42, 984, 484);
frmApp.add(scrollPane);
{
table = new JTable();
table.setFillsViewportHeight(true);
Object[][] data = {
{"I01", "Tom",new Boolean(false), ""},
{"I02", "Jerry",new Boolean(false), ""},
{"I03", "Ann",new Boolean(false), ""}};
String[] cols = {"ID","NAME","DONE","COMMENTS"};
model = new DefaultTableModel(data, cols) {
private static final long serialVersionUID = -7158928637468625935L;
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table.setModel(model);
table.setRowHeight(20);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
int row = table.rowAtPoint(evt.getPoint());
int col = table.columnAtPoint(evt.getPoint());
table.setRowHeight(20);
if(col==3){
table.setRowHeight(row, 100);
//this is where I need it to work as an editorPane if it is only for the selected cell
}
}
});
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
scrollPane.setViewportView(table);
checkbox = new JCheckBox("OK");
checkbox.setHorizontalAlignment(SwingConstants.CENTER);
checkbox.setBounds(360, 63, 97, 23);
}
}
}
}
【问题讨论】:
-
+1 包括MVCE。另一方面,Swing 旨在与Layout Managers 一起使用,因此您应该避免使用诸如
setBounds()、setLocation()、setXxxSize()之类的方法,因为组件的大小和位置是布局管理器的责任。 -
感谢@dic19,我取出了'setBounds()'和'setLocation()',它的工作原理相同,但我确实想要'setXxxSize()'。你还能帮我解决单元格或列的问题吗?
-
是的,它确实有效,但最终你会陷入this answer 中所示的常见陷阱。对于其余的你现在有有用的答案:)
标签: java eclipse swing jtable jeditorpane