Java Tutorial/Swing/JTableHeader — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 17:44, 31 мая 2010

Creating a Custom Column Header Renderer in a JTable Component

import java.awt.ruponent;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable();
    int vColIndex = 0;
    TableColumn col = table.getColumnModel().getColumn(vColIndex);
    col.setHeaderRenderer(new MyTableHeaderRenderer());
  }
}
class MyTableHeaderRenderer extends JLabel implements TableCellRenderer {
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int rowIndex, int vColIndex) {
    setText(value.toString());
    setToolTipText((String) value);
    return this;
  }
}





Customizing a JTableHeader Look and Feel

Property StringObject TypeTableHeader.backgroundColorTableHeader.cellBorderBorderTableHeader.fontFontTableHeader.foregroundColorTableHeaderUIString


Customizing Column Headers with Icons

import java.awt.BorderLayout;
import java.awt.ruponent;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
class JComponentTableCellRenderer implements TableCellRenderer {
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {
    return (JComponent) value;
  }
}
public class LabelHeaderSample {
  public static void main(String args[]) {
    final Object rows[][] = { { "one", "1" }, { "two", "2" }, { "three", "3" } };
    JFrame frame = new JFrame("Label Header");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    String headers[] = { "English", "#" };
    JTable table = new JTable(rows, headers);
    JScrollPane scrollPane = new JScrollPane(table);
    Icon redIcon = new ImageIcon("yourFile.gif");
    Icon blueIcon = new ImageIcon("yourFile.gif");
    Border headerBorder = UIManager.getBorder("TableHeader.cellBorder");
    JLabel blueLabel = new JLabel(headers[0], blueIcon, JLabel.CENTER);
    blueLabel.setBorder(headerBorder);
    JLabel redLabel = new JLabel(headers[1], redIcon, JLabel.CENTER);
    redLabel.setBorder(headerBorder);
    TableCellRenderer renderer = new JComponentTableCellRenderer();
    TableColumnModel columnModel = table.getColumnModel();
    TableColumn column0 = columnModel.getColumn(0);
    TableColumn column1 = columnModel.getColumn(1);
    column0.setHeaderRenderer(renderer);
    column0.setHeaderValue(blueLabel);
    column1.setHeaderRenderer(renderer);
    column1.setHeaderValue(redLabel);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}





Hiding column headers: table.setTableHeader(null);

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class NullColumnHeader {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Object rowData[][] = { { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
        { "Row2-Column1", "Row2-Column2", "Row2-Column3" } };
    Object columnNames[] = { "1", "2", "3" };
    JTable table = new JTable(rowData, columnNames);
    JScrollPane scrollPane = new JScrollPane(table);
    table.setTableHeader(null);
    
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}



You could also remove headers by subclassing JTable and overriding the protected configureEnclosingScrollPane() method, or by telling every TableColumn that its header value is empty.


Implementing Variable-Height Column Headers in a JTable Component

import java.awt.ruponent;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
public class Main {
  public static void main(String[] argv) throws Exception {
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    model.addColumn("Col1");
    model.addColumn("Icon Here");
    table.getColumnModel().getColumn(0).setHeaderValue(new ImageIcon("image.gif"));
    table.getColumnModel().getColumn(0).setHeaderRenderer(new IconHeaderRenderer());
  }
}
class IconHeaderRenderer extends DefaultTableCellRenderer {
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {
    if (table != null) {
      JTableHeader header = table.getTableHeader();
      if (header != null) {
        setForeground(header.getForeground());
        setBackground(header.getBackground());
        setFont(header.getFont());
      }
    }
    if (value instanceof Icon) {
      setIcon((Icon) value);
      setText("");
    } else {
      setText((value == null) ? "" : value.toString());
      setIcon(null);
    }
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setHorizontalAlignment(JLabel.CENTER);
    return this;
  }
}





Listening for Clicks on a Column Header in a JTable Component

import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable(5, 5);
    JTableHeader header = table.getTableHeader();
    header.addMouseListener(new ColumnHeaderListener());
  }
}
class ColumnHeaderListener extends MouseAdapter {
  public void mouseClicked(MouseEvent evt) {
    JTable table = ((JTableHeader) evt.getSource()).getTable();
    TableColumnModel colModel = table.getColumnModel();
    int index = colModel.getColumnIndexAtX(evt.getX());
    if (index == -1) {
      return;
    }
    Rectangle headerRect = table.getTableHeader().getHeaderRect(index);
    if (index == 0) {
      headerRect.width -= 10;
    } else {
      headerRect.grow(-10, 0);
    }
    if (!headerRect.contains(evt.getX(), evt.getY())) {
      int vLeftColIndex = index;
      if (evt.getX() < headerRect.x) {
        vLeftColIndex--;
      }
    }
  }
}





Removing Column Headers: provide empty strings as the column header names.

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class EmptyColumnHeader {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Object rowData[][] = { { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
        { "Row2-Column1", "Row2-Column2", "Row2-Column3" } };
    Object columnNames[] = { "", "", "" };
    JTable table = new JTable(rowData, columnNames);
    JScrollPane scrollPane = new JScrollPane(table);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}





Removing the Column Headers from a Scrollable in a JTable Component

import javax.swing.JTable;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable();
    // Remove the column headers
    table.setTableHeader(null);
  }
}





Setting Column Header Tool Tips in a JTable Components

import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class Main {
  public static void main(String[] argv) throws Exception {
    int rows = 10;
    int cols = 5;
    JTable table = new JTable(rows, cols);
    JTableHeader header = table.getTableHeader();
    ColumnHeaderToolTips tips = new ColumnHeaderToolTips();
    for (int c = 0; c < table.getColumnCount(); c++) {
      TableColumn col = table.getColumnModel().getColumn(c);
      tips.setToolTip(col, "Col " + c);
    }
    header.addMouseMotionListener(tips);
  }
}
class ColumnHeaderToolTips extends MouseMotionAdapter {
  TableColumn curCol;
  Map tips = new HashMap();
  public void setToolTip(TableColumn col, String tooltip) {
    if (tooltip == null) {
      tips.remove(col);
    } else {
      tips.put(col, tooltip);
    }
  }
  public void mouseMoved(MouseEvent evt) {
    JTableHeader header = (JTableHeader) evt.getSource();
    JTable table = header.getTable();
    TableColumnModel colModel = table.getColumnModel();
    int vColIndex = colModel.getColumnIndexAtX(evt.getX());
    TableColumn col = null;
    if (vColIndex >= 0) {
      col = colModel.getColumn(vColIndex);
    }
    if (col != curCol) {
      header.setToolTipText((String) tips.get(col));
      curCol = col;
    }
  }
}





Showing the Table Header in a Non-Scrollable JTable Component

import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
public class Main {
  public static void main(String[] argv) throws Exception {
    int rows = 10;
    int cols = 5;
    JTable table = new JTable(rows, cols);
    JTableHeader header = table.getTableHeader();
    JPanel container = new JPanel(new BorderLayout());
    // Add header in NORTH slot
    container.add(header, BorderLayout.NORTH);
    // Add table itself to CENTER slot
    container.add(table, BorderLayout.CENTER);
  }
}





Using Tooltips in Table Headers: Showing Tooltip Text in a Table Header

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class LabelHeaderSample {
  public static void main(String args[]) {
    final Object rows[][] = { { "one", "1" }, { "two", "2" }, { "three", "3" } };
    JFrame frame = new JFrame("Label Header");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    String headers[] = { "English", "#" };
    JTable table = new JTable(rows, headers);
    JScrollPane scrollPane = new JScrollPane(table);
    JLabel headerRenderer = new DefaultTableCellRenderer();
    String columnName = table.getModel().getColumnName(0);
    headerRenderer.setText(columnName);
    headerRenderer.setToolTipText("text");
    TableColumnModel columnModel = table.getColumnModel();
    TableColumn englishColumn = columnModel.getColumn(0);
    englishColumn.setHeaderRenderer((TableCellRenderer)headerRenderer);
    
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}