Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...