下面列出了javax.swing.JTable#getSelectedRow ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
*
* @Title : setSelectedHist
* @Description: Set first selected history case
* @Param : @param hist
* @Param : @param tab
* @Param : @param tabMdl
* @Return : void
* @Throws :
*/
public static void setSelectedHist(HttpHist hist, JTable tab, TabModel tabMdl)
{
if (null == hist)
{
return;
}
int row = tab.getSelectedRow();
if (row < 0)
{
return;
}
List<Object> rowData = tabMdl.getRow(row);
List<Object> values = hist.toRow(rowData.get(0));
tabMdl.setRowValues(values, row);
}
public void actionPerformed(ActionEvent ae) {
JTable jt = (JTable) ae.getSource();
int row = jt.getSelectedRow();
int col = jt.getSelectedColumn();
if ((row != -1) && (col != -1)) {
if (PropUtils.isLoggable(BaseTable.class)) {
PropUtils.log(BaseTable.class, "Starting edit due to key event for row " + row); //NOI18N
}
jt.editCellAt(row, 1, null);
//Focus will be rerouted to the editor via this call:
jt.requestFocus();
}
}
private static AbstractAction getEncryptAction(final JTable table) {
return new AbstractAction() {
@Override
public void actionPerformed(ActionEvent me) {
try {
int col = table.getSelectedColumn();
int row = table.getSelectedRow();
if (col > -1 && row > -1) {
String data = table.getValueAt(row, col).toString();
table.setValueAt(TMIntegration.encrypt(data), row, col);
}
} catch (HeadlessException ex) {
Logger.getLogger(TMSettingsControl.class.getName())
.log(Level.SEVERE, ex.getMessage(), ex);
}
}
};
}
/**
* @author Andrew
*
* sets all the meta information for the active song
*/
private static void switchMediaMeta(final JTable target) {
final int row = target.getSelectedRow();
final String title = target.getValueAt(row, 0).toString().trim();
final String artist = target.getValueAt(row, 1).toString().trim();
final String time = (String) target.getValueAt(row, 2);
PlayListPanel.setSongInformation(title, artist);
ControlPanel.total().setText(time);
if (Settings.isSavePlayBack()) {
try {
final File parentDir = new File("./data/livestream/");
parentDir.mkdir();
Files.write(Paths.get("./data/livestream/artist.txt"),
artist.getBytes());
Files.write(Paths.get("./data/livestream/title.txt"),
title.getBytes());
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private MouseListener createExpressionEditorMouseListener(final JTable table, final boolean booleanExpected) {
final MouseAdapter mouseListener = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
final int column = table.getSelectedColumn();
if (column == 1) {
table.removeEditor();
final int row = table.getSelectedRow();
final String[] value = new String[]{(String) table.getValueAt(row, column)};
final int i = editExpression(value, booleanExpected);
if (ModalDialog.ID_OK == i) {
table.setValueAt(value[0], row, column);
}
}
}
}
};
return MouseEventFilterFactory.createFilter(mouseListener);
}
private void rebuildPopup(@NotNull final UsageViewImpl usageView,
@NotNull final List<Usage> usages,
@NotNull List<UsageNode> nodes,
@NotNull final JTable table,
@NotNull final JBPopup popup,
@NotNull final UsageViewPresentation presentation,
@NotNull final RelativePoint popupPosition,
boolean findUsagesInProgress) {
ApplicationManager.getApplication().assertIsDispatchThread();
boolean shouldShowMoreSeparator = usages.contains(MORE_USAGES_SEPARATOR);
if (shouldShowMoreSeparator) {
nodes.add(MORE_USAGES_SEPARATOR_NODE);
}
String title = presentation.getTabText();
String fullTitle = getFullTitle(usages, title, shouldShowMoreSeparator, nodes.size() - (shouldShowMoreSeparator ? 1 : 0), findUsagesInProgress);
((AbstractPopup)popup).setCaption(fullTitle);
List<UsageNode> data = collectData(usages, nodes, usageView, presentation);
MyModel tableModel = setTableModel(table, usageView, data);
List<UsageNode> existingData = tableModel.getItems();
int row = table.getSelectedRow();
int newSelection = updateModel(tableModel, existingData, data, row == -1 ? 0 : row);
if (newSelection < 0 || newSelection >= tableModel.getRowCount()) {
TableScrollingUtil.ensureSelectionExists(table);
newSelection = table.getSelectedRow();
}
else {
table.getSelectionModel().setSelectionInterval(newSelection, newSelection);
}
TableScrollingUtil.ensureIndexIsVisible(table, newSelection, 0);
setSizeAndDimensions(table, popup, popupPosition, data);
}
public void DumpPacket()
{
ViewTab vt = this.getViewerTab();
if(vt == null) return;
ViewPane vp = vt.getCurrentViewPane();
if(vp == null) return;
JTable table = vp.getPacketTable();
if(table == null) return;
int id = table.getSelectedRow();
if(id != -1)
{
DataPacket packet = vt.getCurrentViewPane().getGameSessionViewer().getPacket(id);
if(packet != null)
{
String fname = packet.getName();
if(fname == null || fname.isEmpty())
{
fname = String.format("{0}_unk", packet.getPacketId());
}
File file = new File(fname + ".bin");
try {
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.write(packet.getIdData());
raf.write(packet.getData());
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void seekPrevious() {
final JTable table = TabelPanel.table;
if (table != null) {
final int total = table.getRowCount();
final int idx = table.getSelectedRow();
if (total == 0) {
return;
} else if ((idx == -1) && (total == 0)) {
return;
} else if ((idx == -1) && (total > 0)) {
table.setRowSelectionInterval(0, total - 1);
MediaUtils.switchMedia(table);
} else if (idx <= 0) {
table.setRowSelectionInterval(0, total - 1);
MediaUtils.switchMedia(table);
} else {
try {
table.setRowSelectionInterval(0, idx - 1);
MediaUtils.switchMedia(table);
} catch (final Exception e) {
table.setRowSelectionInterval(0, 0);
MediaUtils.switchMedia(table);
}
}
}
}
@Override
public void show(Component c, int x, int y) {
JTable table = (JTable) c;
boolean flg = table.getSelectedRow() != -1;
copyAction.setEnabled(flg);
deleteAction.setEnabled(flg);
super.show(c, x, y);
}
/**
* Moves the selected nullRoww one nullRoww UP., unless it the first
* nullRoww
*
* @param table the target tmodel
*/
public static void moverowup(JTable table) {
int sRow = table.getSelectedRow();
if (sRow > 0) {
((DefaultTableModel) table.getModel()).moveRow(sRow, sRow, sRow - 1);
table.getSelectionModel().setSelectionInterval(sRow - 1, sRow - 1);
}
}
/**
* Get the alias of the entry currently selected in the KeyStore table if
* any.
*
* @return Alias or null if none selected
*/
public String getSelectedEntryAlias() {
JTable jtKeyStore = getActiveKeyStoreTable();
int row = jtKeyStore.getSelectedRow();
if (row == -1) {
return null;
}
return (String) jtKeyStore.getValueAt(row, 3);
}
/**
* get all selected rows and DELETE one by one from the last.
*
* @param table the table to DELETE rows
*/
public static void deleterow(JTable table) {
int[] selectedrows = table.getSelectedRows();
for (int row : selectedrows) {
row = table.getSelectedRow();
if (table.getRowSorter() != null) {
row = table.getRowSorter().convertRowIndexToModel(row);
}
((DefaultTableModel) table.getModel()).removeRow(row);
}
}
/**
* Inserts new row if any row is selected else adds new row at the end
*
* @param table
*/
public static void addrow(JTable table) {
int rowindex = table.getRowCount();
if (table.getSelectedRow() > -1) {
((DefaultTableModel) table.getModel()).addRow(nullRow);
((DefaultTableModel) table.getModel()).moveRow(table.getRowCount() - 1, table.getRowCount() - 1, table.getSelectedRow());
rowindex = table.getSelectedRow();
} else {
((DefaultTableModel) table.getModel()).addRow(nullRow);
}
table.scrollRectToVisible(new Rectangle(table.getCellRect(rowindex, 0, true)));
}
/**
* @author Andrew
*
* switches the album cover
*/
public static void copyMediaURL(final JTable target) {
final int row = target.getSelectedRow();
final String link = (String) target.getValueAt(row, 7);
final StringSelection stringSelection = new StringSelection(link);
final Clipboard clpbrd = Toolkit.getDefaultToolkit()
.getSystemClipboard();
clpbrd.setContents(stringSelection, null);
}
/**
* This method retrieves the key-code {@code keyCode} of a released key in
* the JTable {@code table} and checks whether this key was a navigation key
* (i.e. cursor up/down/left/right or home/end). If so, the method tries to
* select the next related entry of that JTable, according to the pressed
* key.<br><br>
* Furthermore, the related content is made visible (scroll rect to visible
* or ensure index is visible).
*
* @param table a reference to the JTable where the related key was released
* @param keyCode the keycode of the released key
*/
public static void navigateThroughList(JTable table, int keyCode) {
if (KeyEvent.VK_LEFT == keyCode || KeyEvent.VK_RIGHT == keyCode) {
return;
}
int selectedRow = table.getSelectedRow();
if (-1 == selectedRow) {
selectedRow = 0;
}
switch (keyCode) {
case KeyEvent.VK_HOME:
selectedRow = 0;
break;
case KeyEvent.VK_END:
selectedRow = table.getRowCount() - 1;
break;
case KeyEvent.VK_DOWN:
if (table.getRowCount() > (selectedRow + 1)) {
selectedRow++;
}
break;
case KeyEvent.VK_UP:
if (selectedRow > 0) {
selectedRow--;
}
break;
}
table.getSelectionModel().setSelectionInterval(selectedRow, selectedRow);
table.scrollRectToVisible(table.getCellRect(selectedRow, 0, false));
}
private void calibrate(final JTable table) {
final int row = table.getSelectedRow();
if (row == -1) return;
VisualVM.getInstance().runTask(new Runnable() {
public void run() {
Runnable refresher = new Runnable() { public void run() { refreshTimes(table); } };
CalibrationSupport.calibrate(javaPlatforms[row], -1, null, refresher);
}
});
}
public static void repeat() {
final JTable table = TabelPanel.table;
if (table != null) {
if (table.getRowCount() > 0) {
final int index = table.getSelectedRow();
table.setRowSelectionInterval(0, index);
MediaUtils.switchMedia(table);
} else {
}
}
}
@Override
public void onClick(ActionEvent arg0)
{
HData v_HData = new HData();
v_HData.setRowKey( ((JTextComponent)XJava.getObject("Edit_RowKey")) .getText().trim());
v_HData.setFamilyName(((JComboBox) XJava.getObject("Edit_FamilyName")) .getSelectedItem().toString().trim());
v_HData.setColumnName(((JComboBox) XJava.getObject("Edit_ColumnName")) .getSelectedItem().toString().trim());
v_HData.setValue( ((JTextComponent)XJava.getObject("Edit_ColumnValue")).getText().trim());
if ( JavaHelp.isNull(v_HData.getRowKey()) )
{
this.getAppFrame().showHintInfo("提交时,行主键不能为空!" ,Color.RED);
((JComponent)XJava.getObject("Edit_RowKey")).requestFocus();
return;
}
if ( JavaHelp.isNull(v_HData.getFamilyName()) )
{
this.getAppFrame().showHintInfo("提交时,列族名不能为空!" ,Color.RED);
((JComponent)XJava.getObject("Edit_FamilyName")).requestFocus();
return;
}
if ( JavaHelp.isNull(v_HData.getColumnName()) )
{
this.getAppFrame().showHintInfo("提交时,字段名不能为空!" ,Color.RED);
((JComponent)XJava.getObject("Edit_ColumnName")).requestFocus();
return;
}
try
{
HData v_OldHData = (HData)this.getHBase().getValue(this.getTableName() ,v_HData);
this.getHBase().update(this.getTableName() ,v_HData);
// 重新从数据库是查询一次,主要想获取时间戳
HData v_NewHData = (HData)this.getHBase().getValue(this.getTableName() ,v_HData);
JTable v_JTable = (JTable)XJava.getObject("xtDataList");
int v_RowNo = v_JTable.getSelectedRow();
int v_OptType = 1; // 操作类型(0:修改 1:添加)
if ( v_JTable.getSelectedRowCount() == 1 )
{
if ( v_NewHData.getRowKey().equals(v_JTable.getValueAt(v_RowNo ,1)) )
{
if ( v_NewHData.getFamilyName().equals(v_JTable.getValueAt(v_RowNo ,2)) )
{
if ( v_NewHData.getColumnName().equals(v_JTable.getValueAt(v_RowNo ,3)) )
{
v_OptType = 0;
}
}
}
}
if ( v_OptType == 0 )
{
v_JTable.setValueAt(v_NewHData.getValue().toString() ,v_RowNo ,4);
v_JTable.setValueAt(v_NewHData.getTimestamp() ,v_RowNo ,5);
v_JTable.setValueAt(v_NewHData.getTime().getFullMilli() ,v_RowNo ,6);
this.getAppFrame().showHintInfo("修改完成!" ,Color.BLUE);
}
else
{
this.getAppFrame().setRowCount(this.getAppFrame().getRowCount() + 1);
this.getAppFrame().getTableModel().addRow(SubmitActionListener.$MY.toObjects(this.getAppFrame().getRowCount() ,v_NewHData));
if ( v_OldHData != null )
{
this.getAppFrame().showHintInfo("修改完成,请刷新查询结果。" ,Color.BLUE);
}
else
{
this.getAppFrame().showHintInfo("添加完成!" ,Color.BLUE);
}
}
}
catch (Exception exce)
{
this.getAppFrame().showHintInfo("修改异常:" + exce.getMessage() ,Color.RED);
}
}
@Override
public void mouseClicked(MouseEvent e) {
JTableHeader h = (JTableHeader) e.getSource();
JTable table = h.getTable();
int selectedRow = table.getSelectedRow();
TableModel model = table.getModel();
//remember selection to keep after sorting
Object selectedAction=null;
int objectColumn=-1;
if(selectedRow>-1) {
for(int i=0; i<table.getColumnCount(); i++) {
//first find colum with appropriate object
if(model.getValueAt(selectedRow, i) instanceof ActionHolder) {
//remember this object
selectedAction=model.getValueAt(selectedRow, i);
objectColumn=i;
//stop edition as we click somewhere ouside of editor
TableCellEditor editor=table.getCellEditor();
if(editor!=null) {
editor.stopCellEditing();
}
break;
}
}
}
TableColumnModel columnModel = h.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = columnModel.getColumn(viewColumn).getModelIndex();
if (column != -1) {
int status = getSortingStatus(column);
if (!e.isControlDown()) {
cancelSorting();
}
// Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
// {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
status = status + (e.isShiftDown() ? -1 : 1);
status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
setSortingStatus(column, status);
//reselect the same object
if(selectedAction!=null)setSelectedRow(table, selectedAction, objectColumn);
}
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
Input<?> in = (Input<?>)value;
String str;
// 1) Keyword
if (column == 0) {
str = in.getKeyword();
}
// 2) Default value
else if (column == 1) {
if (in.getDefaultText() != null)
str = EditBox.formatEditorText(in.getDefaultText());
else {
str = in.getDefaultString();
if (str == null || str.isEmpty())
str = EditBox.NONE;
}
}
// 3) Present value
else {
str = in.getValueString();
if (!in.isValid())
str = EditBox.formatErrorText(str);
if (in.isDefault() && in.isRequired())
str = EditBox.REQD;
if (in.isLocked())
str = EditBox.formatLockedText(str);
}
// Pass along the keyword string, not the input itself
Component cell = super.getTableCellRendererComponent(table, str, isSelected, hasFocus, row, column);
if (row == table.getSelectedRow())
cell.setBackground(FrameBox.TABLE_SELECT);
else
cell.setBackground(null);
if (hasFocus)
this.setBorder(focusBorder);
else
this.setBorder(border);
return cell;
}