Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

java - Get position of Click JTable while using Cell renderer

I'm currently using a JTable in Java to display a large amount of text information, and as such have implemented text wrapping, using the following code:

MyCellRenderer mcr = new MyCellRenderer();
table.getColumnModel().getColumn(0).setCellRenderer(mcr);

class MyCellRenderer extends JTextArea implements TableCellRenderer {
  public MyCellRenderer() {
setLineWrap(true);
setWrapStyleWord(true);

 }

public Component getTableCellRendererComponent(JTable table, Object
    value, boolean isSelected, boolean hasFocus, int row, int column) {
setText(value.toString());
setSize(table.getColumnModel().getColumn(column).getWidth(),
        getPreferredSize().height);
if (table.getRowHeight(row) != getPreferredSize().height) {
        table.setRowHeight(row, getPreferredSize().height);
}
return this;
}
} 

However, when this is implemented, any attempt to detect the cell which is clicked, simply returns "-1" (out of bounds) as the point of click, I am using the following code to detect the click location:

table.addMouseListener(new java.awt.event.MouseAdapter() {

  public void mouseClicked(java.awt.event.MouseEvent e) {
    int row = table.rowAtPoint( e.getPoint() );
    int column = table.columnAtPoint( e.getPoint() );
  }
});
}

Is there any way, whilst maintaining the text wrapping, that I can text the cell which is clicked in the JTable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

My current situation requires a large amount of text information to be displayed next to [the] relevant data

Instead of a MouseListener, add a TableModelListener to your TableModel and update the Document model of an adjacent JTextComponent. In this related example, the TableModelListener updates the ListModel of an adjacent JList.

Alternatively, add a ListSelectionListener to your table's ListSelectionModel and update an adjacent component accordingly. In this related example using SINGLE_SELECTION, the ListSelectionListener updates an adjacent JButton.

Alternatively, look at this TablePopupEditor, which uses a JButton as a TableCellEditor. The button's ActionListener evokes a popup modal JDialog containing a JTextArea.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...