[英]JTable selection listener
我有一个代码在applet中显示Table并包含两列: -
这是我的代码:
import javax.swing.table.*;
public class TableIcon extends JFrame
{
public TableIcon()
{
ImageIcon aboutIcon = new ImageIcon("about16.gif");
ImageIcon addIcon = new ImageIcon("add16.gif");
ImageIcon copyIcon = new ImageIcon("copy16.gif");
String[] columnNames = {"Picture", "Description"};
Object[][] data =
{
{aboutIcon, "About"},
{addIcon, "Add"},
{copyIcon, "Copy"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
}
public static void main(String[] args)
{
TableIcon frame = new TableIcon();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
现在我想知道的是如何在我的表上实现选择监听器或鼠标监听器事件,这样它应该从我的表中选择一个特定的图像并显示在文本区域或文本字段上(我的表包含图像文件的路径)?
我可以在框架上的桌子和桌子上添加文本字段吗? 如果需要,请随时询问。
在我的代码中,我有一个表格,我设置单一选择模式; 在我的例子中, 如何编写列表选择侦听器 (带有从getMinSelectionIndex到getMaxSelectionIndex的for循环)中描述的侦听器没有用,因为释放鼠标按钮我确定我只选择了一行。
所以我解决了如下:
....
int iSelectedIndex =-1;
....
JTable jtable = new JTable(tableModel); // tableModel defined elsewhere
jtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ListSelectionModel selectionModel = jtable.getSelectionModel();
selectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
handleSelectionEvent(e);
}
});
....
protected void handleSelectionEvent(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
// e.getSource() returns an object like this
// javax.swing.DefaultListSelectionModel 1052752867 ={11}
// where 11 is the index of selected element when mouse button is released
String strSource= e.getSource().toString();
int start = strSource.indexOf("{")+1,
stop = strSource.length()-1;
iSelectedIndex = Integer.parseInt(strSource.substring(start, stop));
}
我认为这个解决方案,在启动和停止之间不需要for循环来检查选择哪个元素,当表处于单选模式时更合适
这个怎么样?
protected void handleSelectionEvent(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
final DefaultListSelectionModel target = (DefaultListSelectionModel)e.getSource();
iSelectedIndex = target.getAnchorSelectionIndex();
}
阅读Swing教程中有关如何编写列表选择侦听器的部分 。
您不能向表中添加文本字段,但可以将文本字段和表添加到同一帧中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.