Swing/PlaceholderForEmptyTable のバックアップの現在との差分(No.6)
-
category: swing
folder: PlaceholderForEmptyTable
title: JTableが空の場合、中央にJComponentを表示する
tags: [JTable, JEditorPane, GridBagLayout, URL]
author: aterai
pubdate: 2010-09-13T11:14:48+09:00
description: JTableが空の場合、表領域の中央に任意のJComponentが表示されるように設定します。
image:
hreflang:
href: https://java-swing-tips.blogspot.com/2010/09/placeholder-for-empty-jtable.html lang: en
概要
概要
JTable
が空の場合、表領域の中央に任意のJComponent
が表示されるように設定します。
Screenshot
Advertisement
サンプルコード
サンプルコード
#spandel
JEditorPane hint = new JEditorPane("text/html", "<html><a href='dummy'>No data!</a></html>");
#spanend
#spanadd
String placeholder = "<html>No data! <a href='#placeholder'>Input hint(beep)";
#spanend
#spanadd
JEditorPane hint = new JEditorPane("text/html", placeholder);
#spanend
#spanadd
hint.setOpaque(false);
#spanend
#spanadd
hint.setEditable(false);
#spanend
#spanadd
hint.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
#spanend
#spanadd
hint.addHyperlinkListener(e -> {
#spanend
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
UIManager.getLookAndFeel().provideErrorFeedback((Component) e.getSource());
}
#spanadd
});
#spanend
table.setFillsViewportHeight(true);
table.setLayout(new GridBagLayout());
table.add(hint);
model.addTableModelListener(new TableModelListener() {
@Override public void tableChanged(TableModelEvent e) {
DefaultTableModel model = (DefaultTableModel) e.getSource();
hint.setVisible(model.getRowCount() == 0);
}
});
View in GitHub: Java, Kotlin解説
上記のサンプルでは、JTable
に編集不可にしたJEditorPane
を追加し、以下のように設定して、常に中央にレイアウトされるように設定しています。
解説
-
JTable#setFillsViewportHeight(true)
としてJTable
の高さがJViewport
の高さより小さい場合、両者が同じ高さになるように設定 -
JTable
のレイアウトをnull
からGridBagLayout
に変更して追加した編集不可のJEditorPane
が中央に配置されるよう設定 -
TableModelListener#tableChanged(...)
イベントが発生したときモデルに行が存在するかどうかでJEditorPane
の表示・非表示を切り替える
-
JTable#setFillsViewportHeight(true)
として、JTable
の高さがJViewport
の高さより小さい場合、両者が同じ高さになるように設定 -
JTable
のレイアウトをnull
から、GridBagLayout
に変更
参考リンク
JEditorPane
の表示非表示の切り替えは、ポップアップメニューで行の追加削除を行ったとき、JTable#getRowCount()==0
かどうかで判断しています。TableModelListener
を使って行の追加削除を行ったときにJEditorPane
の表示非表示を切り替えるように変更しました。