Swing/PlaceholderForEmptyTable のバックアップの現在との差分(No.12)
- 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#setFillsViewportHeight(true)
としてJTable
の高さがJViewport
の高さより小さい場合、両者が同じ高さになるように設定-
JTable
のレイアウトをnull
からGridBagLayout
に変更し、追加した編集不可のJEditorPane
が中央に配置されるよう設定 -
TableModelListener#tableChanged(...)
イベントが発生したとき、モデルに行が存在するかどうかでJEditorPane
の表示・非表示を切り替え -
JTable
のレイアウトをnull
からGridBagLayout
に変更して追加した編集不可のJEditorPane
が中央に配置されるよう設定 -
TableModelListener#tableChanged(...)
イベントが発生したときモデルに行が存在するかどうかでJEditorPane
の表示・非表示を切り替える