TITLE:JTableHeaderをクリックしてそのColumnのセルを全選択

JTableHeaderをクリックしてそのColumnのセルを全選択

編集者:Terai Atsuhiro~

作成日:2005-04-04
更新日:2021-10-26 (火) 23:59:10
  • category: swing folder: ColumnSelection title: JTableHeaderをクリックしてそのColumnのセルを全選択 tags: [JTable, JTableHeader, MouseListener] author: aterai pubdate: 2005-04-04T03:22:43+09:00 description: JTableHeaderをクリックしたとき、そのColumn以下にあるセルを全選択します。 image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTJrC8DyhI/AAAAAAAAAUw/SO1wMAudBiE/s800/ColumnSelection.png

概要

JTableHeaderをクリックしたとき、そのColumn以下にあるセルを全選択します。

概要

JTableHeaderをクリックしたとき、そのColumn以下にあるセルを全選択します。

#screenshot

サンプルコード

#spanend
#spandel
JTextArea textArea = new JTextArea("ComponentPopupMenu Test");
#spanend
#spandel
textArea.setComponentPopupMenu(new TextComponentPopupMenu(textArea));
#spanend
#spandel
#spanend
#spandel
table = new JTable(model) {
#spanend
  private final Color evenColor = new Color(250, 250, 250);
  @Override
  public Component prepareRenderer(TableCellRenderer tcr, int row, int column) {
    Component c = super.prepareRenderer(tcr, row, column);
    if(isCellSelected(row, column)) {
      c.setForeground(getSelectionForeground());
      c.setBackground(getSelectionBackground());
    }else{
      c.setForeground(getForeground());
      c.setBackground((row%2==0)?evenColor:getBackground());
    }
    return c;
  }
#spandel
};
#spanend
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#spanend
#spanadd
JTable table = new JTable(model);
#spanend
table.setCellSelectionEnabled(true);
#spandel
final JTableHeader header = table.getTableHeader();
#spanend
#spanadd
JTableHeader header = table.getTableHeader();
#spanend
header.addMouseListener(new MouseAdapter() {
  public void mousePressed(MouseEvent e) {
    if(!check.isSelected()) return;
    if(table.isEditing()) {
  @Override public void mousePressed(MouseEvent e) {
    if (!check.isSelected()) {
      return;
    }
    if (table.isEditing()) {
      table.getCellEditor().stopCellEditing();
    }
    int col = header.columnAtPoint(e.getPoint());
    table.changeSelection(0, col, false, false);
    table.changeSelection(table.getRowCount()-1, col, false, true);
    table.changeSelection(table.getRowCount() - 1, col, false, true);
  }
});
  • &jnlp;
  • &jar;
  • &zip;

解説

上記のサンプルでは、JTableHeaderにマウスリスナーを追加し、JTableHeader#columnAtPoint(Point)メソッドを使って、クリックされたColumnを取得するようになっています。

解説

上記のサンプルでは、JTableHeaderMouseListenerを追加し、JTableHeader#columnAtPoint(Point)メソッドを使ってマウスでクリックされた位置にあるTableColumnを取得しています。 Column全体の選択は、changeSelectionメソッドを二回使用することで行っています。
  • TableColumn全体の選択はchangeSelectionメソッドを2回使用することで実現している

参考リンク

参考リンク

コメント

コメント