gpt4 book ai didi

java - JTable 单元格似乎可以无缘无故地调整大小

转载 作者:行者123 更新时间:2023-12-01 12:47:05 24 4
gpt4 key购买 nike

我有一个从 hibernate 状态填充的 Jtable。尽管表位于 jscrollpane 内部,但所有字段都填充得很好。我将表的 dbData.setPreferredScrollableViewportSize 设置如下:

dbData.setPreferredScrollableViewportSize(dbData.getPreferredSize());

dbScrollPane = new JScrollPane(null, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
dbScrollPane.getViewport().add(dbData);
Universalvars.setUpdatePane(dbScrollPane);
dbScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
dbScrollPane.setSize(750, 725);

dbScrollPane.setLocation(25, 0);

this.add(dbScrollPane);

现在,在表中填充了来自 hibernate 和 mysql 的数据后,我调整了每列的宽度,这反过来又使得 block 中的文本区域变得更长,因为文本高度所需的空间更少。执行此操作后,行的大小不会调整。

现在相关表有 15 列。只有前 7 个在视口(viewport)中可见,并且是 1 行文本 block 。当我在 Jscrollpane 中滚动以查看较大的文本 block 单元格时,表格会自动增加单元格的高度,尽管它仍然留下空白区域。

我希望这是有道理的,因为发布所有项目代码可能会非常过多。不管怎样,有没有办法得到它,以便我可以将单元格设置为一定的宽度和行高,以匹配它们应该包含的文本量?就像如果所有列在该行中都有一行文本,我不需要它的高度为 200 px,但如果有一行有一列有 500 个文本字符并且单元格为 300,则同样如此px 宽,那么整行需要更高。尽管它不需要具有容纳所述文本所需的两倍或三倍的空间量。

有什么想法吗?提前致谢。

最佳答案

不要使用getViewport().add(...),使用getViewport().setView(...)

这是因为视口(viewport)在概念上控制单个 View 并以特殊方式实现。

不要使用setSizesetLocation,这建议使用null布局,这在运行时会导致问题不同的系统,具有不同的字体和渲染管道。坚持使用布局管理 API,它会让生活变得更简单

已更新

首先,不要从单元格渲染器内以任何方式修改表或模型的状态,这将导致一系列永无休止的更新。

其次,使用 TableModelListener 监视表状态的更改,并使用 TableColumnModelListener 监视列模型的更改

当您检测到其中任何一个发生变化时,您需要探测适当的单元格渲染器以确定其首选大小并相应地调整列/行大小。

请确保,您不会因为调整引发的事件而进行调整;)

已更新示例

这是一个非常基本的示例,可以尝试并大致了解如何实现此目标...

enter image description here

import java.awt.Color;
import java.awt.Component;
import static java.awt.Component.TOP_ALIGNMENT;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

public class VariableTable {

public static void main(String[] args) {
new VariableTable();
}

private JTable table;
private boolean ignoreUpdates;

public VariableTable() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

table = new JTable(loadTableModel());
table.getColumnModel().getColumn(2).setCellRenderer(new TextAreaRenderer());

table.getModel().addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
updateTableProperties();
}
});
table.getColumnModel().addColumnModelListener(new TableColumnModelListener() {

@Override
public void columnAdded(TableColumnModelEvent e) {
updateTableProperties();
}

@Override
public void columnRemoved(TableColumnModelEvent e) {
updateTableProperties();
}

@Override
public void columnMoved(TableColumnModelEvent e) {
updateTableProperties();
}

@Override
public void columnMarginChanged(ChangeEvent e) {
updateTableProperties();
}

@Override
public void columnSelectionChanged(ListSelectionEvent e) {
}
});

updateTableProperties();

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

protected void updateTableProperties() {
if (!ignoreUpdates) {
ignoreUpdates = true;
try {
for (int i = 0; i < table.getColumnCount() - 1; i++) {
adjustColumnSizes(i, 2);
}
adjustJTableRowSizes(2);
} finally {
ignoreUpdates = false;
}
}
}

private void adjustJTableRowSizes(int column) {
for (int row = 0; row < table.getRowCount(); row++) {
int maxHeight = 0;
TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
Object valueAt = table.getValueAt(row, column);
Component tableCellRendererComponent = cellRenderer.getTableCellRendererComponent(table, valueAt, false, false, row, column);

DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
TableColumn tc = colModel.getColumn(column);

int heightPreferable = tableCellRendererComponent.getPreferredSize().height;
tableCellRendererComponent.setSize(tc.getWidth(), heightPreferable);
heightPreferable = tableCellRendererComponent.getPreferredSize().height;

maxHeight = Math.max(heightPreferable, maxHeight);
table.setRowHeight(row, maxHeight);
}

}

public void adjustColumnSizes(int column, int margin) {
DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
TableColumn col = colModel.getColumn(column);
int width;

TableCellRenderer renderer = col.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
width = comp.getPreferredSize().width;

for (int r = 0; r < table.getRowCount(); r++) {
renderer = table.getCellRenderer(r, column);
comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, column), false, false, r, column);
int currentWidth = comp.getPreferredSize().width;
width = Math.max(width, currentWidth);
}

width += 2 * margin;

col.setPreferredWidth(width);
col.setWidth(width);
// col.setMinWidth(width);
col.setMaxWidth(width);
}

public TableModel loadTableModel() {

DefaultTableModel model = new DefaultTableModel(
new String[]{"Chapter", "Paragraph", "Text"}, 0);

int chapter = 0;
int paragraph = 0;
try (BufferedReader br = new BufferedReader(new FileReader(new File("Book.txt")))) {

String text = null;
while ((text = br.readLine()) != null) {
if (text.startsWith("Chapter:")) {
chapter++;
paragraph = 0;
} else if (text.trim().length() > 0) {
paragraph++;
model.addRow(new Object[]{
chapter,
paragraph,
text
});
}
}

} catch (IOException exp) {
exp.printStackTrace();;
}

return model;

}

public static class TextAreaRenderer extends JTextArea implements TableCellRenderer {

protected static Border NOT_SELECTED_BORDER = new EmptyBorder(1, 1, 1, 1);

public TextAreaRenderer() {
setLineWrap(true);
setWrapStyleWord(true);
this.setAlignmentY(TOP_ALIGNMENT);
setBorder(NOT_SELECTED_BORDER);
setColumns(20);
}

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
setText(value.toString());

if (table == null) {
return this;
}

Color fg = null;
Color bg = null;

JTable.DropLocation dropLocation = table.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsertRow()
&& !dropLocation.isInsertColumn()
&& dropLocation.getRow() == row
&& dropLocation.getColumn() == column) {

fg = UIManager.getColor("Table.dropCellForeground");
bg = UIManager.getColor("Table.dropCellBackground");

isSelected = true;
}

if (isSelected) {
setForeground(fg == null ? table.getSelectionForeground()
: fg);
setBackground(bg == null ? table.getSelectionBackground()
: bg);
} else {
Color background = table.getBackground();
if (background == null || background instanceof javax.swing.plaf.UIResource) {
Color alternateColor = UIManager.getColor("Table.alternateRowColor");
if (alternateColor != null && row % 2 != 0) {
background = alternateColor;
}
}
setForeground(table.getForeground());
setBackground(background);
}

setFont(table.getFont());

if (hasFocus) {
Border border = null;
if (isSelected) {
border = UIManager.getBorder("Table.focusSelectedCellHighlightBorder");
}
if (border == null) {
border = UIManager.getBorder("Table.focusCellHighlightBorder");
}
setBorder(border);

if (!isSelected && table.isCellEditable(row, column)) {
Color col;
col = UIManager.getColor("Table.focusCellForeground");
if (col != null) {
super.setForeground(col);
}
col = UIManager.getColor("Table.focusCellBackground");
if (col != null) {
super.setBackground(col);
}
}
} else {
setBorder(NOT_SELECTED_BORDER);
}

return this;
}

}
}

关于java - JTable 单元格似乎可以无缘无故地调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24592193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com