---
category: swing
folder: VerticalRulesTable
title: JTableに列罫線を描画する
title-en: Drawing column borders in a JTable
tags: [JTable, JLayer, JScrollPane, JTableHeader]
author: aterai
pubdate: 2025-12-29T01:37:17+09:00
description: JTableを中央の列で二分割する二重垂直線を描画します。
summary-jp: JTableを中央の列で二分割する二重垂直線を描画します。
summary-en: Draws a double vertical line dividing the JTable into two parts down the center column.
image: https://drive.google.com/uc?id=1lecLFGLugFzK8iuPaFt-2eAggS8zqoE-
---
* Summary [#summary]
JTableを中央の列で二分割する二重垂直線を描画します。
`JTable`を中央の列で二分割する二重垂直線を描画します。
// #en{{Draws a double vertical line dividing the JTable into two parts down the center column.}}
#download(https://drive.google.com/uc?id=1lecLFGLugFzK8iuPaFt-2eAggS8zqoE-)
* Source Code Examples [#sourcecode]
#code(link){{
class VerticalRulesLayerUI extends LayerUI<JScrollPane> {
@Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (c instanceof JLayer) {
Component view = ((JLayer<?>) c).getView();
if (view instanceof JScrollPane) {
JScrollPane scroll = (JScrollPane) view;
JViewport viewport = scroll.getViewport();
JTable table = (JTable) viewport.getView();
paintVerticalRules(g, table, scroll);
}
}
}
private void paintVerticalRules(Graphics g, JTable table, JComponent parent) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(UIManager.getColor("Table.gridColor"));
int columnCount = table.getModel().getColumnCount();
if (columnCount % 2 == 0) {
int center = columnCount / 2 - 1;
double x1 = table.getCellRect(0, center, false).getMaxX();
Rectangle r = SwingUtilities.calculateInnerArea(parent, null);
g2.draw(new Line2D.Double(x1, r.getY(), x1, r.getHeight()));
double x2 = x1 + 2d; //table.getCellRect(0, center + 1, false).getMinX() + 2d;
g2.draw(new Line2D.Double(x2, r.getY(), x2, r.getHeight()));
g2.dispose();
}
}
}
}}
* Description [#description]
- `JTable`と`JTableHeader`の親となる`JScrollPane`を`JLayer`でラップして両方の描画を上書きする二重垂直罫線を作成・描画する
- `JTable`の列罫線は`JTable#setShowVerticalLines(false)`で非表示化
- `JTable`の内部セル余白も`setIntercellSpacing(new Dimension())`で垂直・水平方向ともに`0`に変更
- `JTableHeader#setReorderingAllowed(false)`で列の入れ替えを実行不可に設定
- `JTable#getCellRect(0, center, false)`で取得したセル領域の右端に二重線を描画するので、列幅の変更中の描画は可能
- 二重垂直線の高さは`SwingUtilities.calculateInnerArea(scroll, null)`で取得した親`JScrollPane`の高さを使用して`JTable`内の行数は考慮しない
* Reference [#reference]
- [[JTableの水平罫線を描画する位置とその色をソート条件に応じて変更する>Swing/StandingsTables]]
- [[JTableの列の境界上に追加挿入カーソルを表示する>Swing/InsertTableColumn]]
- [[JSeparatorで段落罫線を描画する>Swing/ColumnRules]]
* Comment [#comment]
#comment
#comment