如何使单元格表现得像可编辑但只读? [英] How to make a cell behave like it's editable but have it read only?
本文介绍了如何使单元格表现得像可编辑但只读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个JTable,我希望其中的单元格具有可编辑单元格时的行为,但是换句话说,这些单元格是不可编辑的(只读).因此,如果我双击一个单元格,则只能选择该单元格中的文本并从该单元格中复制文本.
I have a JTable in which I want the cells to behave the way it behaves when you have the cells editable, but the cells cannot be editable, in other terms, read only. So if I double click on a cell, I should only be able to select text within the cell and copy text from that cell.
推荐答案
是否可以防止用户进行任何更改?
is it possible to prevent the user to make any changes?
您将需要使用自定义编辑器:
You would need to use a custom editor:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.*;
public class TableCopyEditor extends JPanel
{
public TableCopyEditor()
{
String[] columnNames = {"Editable", "Non Editable"};
Object[][] data =
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
// Create a non-editable editor, but still allow text selection
Caret caret = new DefaultCaret()
{
public void focusGained(FocusEvent e)
{
setVisible(true);
setSelectionVisible(true);
}
};
caret.setBlinkRate( UIManager.getInt("TextField.caretBlinkRate") );
JTextField textField = new JTextField();
textField.setEditable(false);
textField.setCaret(caret);
textField.setBorder(new LineBorder(Color.BLACK));
DefaultCellEditor dce = new DefaultCellEditor( textField );
table.getColumnModel().getColumn(1).setCellEditor(dce);
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Table Copy Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TableCopyEditor() );
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
这篇关于如何使单元格表现得像可编辑但只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文