我正在尝试创建一个包含 N 行和 2 列的面板,其中第一列是具有可变长度但在一定限制内的标签(它根据语言改变长度),而第二列包含可能很长的字段文本。
我已经尝试使用 NetBeans 使用 GridBagLayout,但是在缩放面板或添加非常长的字段时结果很混乱。在 JPanel 的屏幕截图下面看看我的意思:
我希望左列与左边框隔开,第一列永远不会调整为小于其最长标签的值(标签必须始终可读),而第二列应该可视化到其可用的水平空间和然后显示点(而不是裁剪文本)。
同样无聊的是,尽管我将 NorthWest 定义为方向,但面板显示在中心垂直对齐
编辑:我使用 TableColumnAdjuster 来使用表格行而不是标签作为我的值,以便我可以用鼠标选择值。我仍然有行但是适合文本的长度而不是包含面板的长度:
public class TestPanel extends JPanel
{
private static ArrayList<String> columnNames = new ArrayList<>();
static JTable table;
MyTableModel myTableModel = new MyTableModel();
static class MyTableModel extends AbstractTableModel
{
private String[] columnNames =
{
"Name", "Value"
};
private Object[][] data =
{
{ "Subject", "very very very very very very very very very very very very very very very very long subject"},
{ "Date", "" },
{ "Location", "" },
{ "Status", "" },
{ "Notes", "" }
};
@Override
public int getColumnCount()
{ return columnNames.length; }
@Override
public int getRowCount()
{ return data.length; }
@Override
public String getColumnName(int col)
{ return columnNames[col]; }
@Override
public Object getValueAt(int row, int col)
{ return data[row][col]; }
@Override
public Class getColumnClass(int c)
{ return getValueAt(0, c).getClass(); }
@Override
public boolean isCellEditable(int row, int col)
{ return false; }
@Override
public void setValueAt(Object value, int row, int col)
{ }
}
public TestPanel()
{
table = new JTable(myTableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(table);
tca.adjustColumns();
JPanel panel = new JPanel(new GridBagLayout());
panel.add(table);
GridBagConstraints constraints = new GridBagConstraints();
constraints.weighty = 1.0;
constraints.fill = GridBagConstraints.VERTICAL;
panel.add(Box.createGlue(), constraints);
add(panel);
}
public static void main(String args[])
{
JFrame frame = new JFrame();
frame.setContentPane(new TestPanel());
frame.setSize(300, 800);
frame.setVisible(true);
}
}
而 TableColumnAdjuster 来自TableColumnAdjuster .. 我得到的仍然如下