【问题标题】:Java SWT: How to center content of a column in a Table?Java SWT:如何将表中列的内容居中?
【发布时间】:2018-09-17 15:28:54
【问题描述】:

我需要将表格第四列的单元格内容居中,现在它们从左侧开始。

这是桌子:

    Table membersTable = new Table(clubComposite, SWT.BORDER | SWT.CHECK | SWT.FULL_SELECTION);
    membersTable.setLinesVisible(true);
    membersTable.setHeaderVisible(true);
    membersTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    TableColumn tblclmnName = new TableColumn(membersTable, SWT.NONE);
    tblclmnName.setWidth(150);
    tblclmnName.setText("Nombre");

    TableColumn tblclmnCommonPhoneNumber = new TableColumn(membersTable, SWT.NONE);
    tblclmnCommonPhoneNumber.setWidth(120);
    tblclmnCommonPhoneNumber.setText("Teléfono");

    TableColumn tblclmnCommonMoney = new TableColumn(membersTable, SWT.NONE);
    tblclmnCommonMoney.setWidth(150);
    tblclmnCommonMoney.setText("Participación Habitual");

    TableColumn tblclmnPayed = new TableColumn(membersTable, SWT.CENTER);
    tblclmnPayed.setWidth(50);
    tblclmnPayed.setText("Pagado"); 

    // populate Table
    for (int i=0; i<50; i++) {
        TableItem tableItem = new TableItem(membersTable, SWT.CENTER);                  
        tableItem.setText(new String[] {"person "+i, "610610620", "100", ""});
        tableItem.setImage(3, uncheckedImage);
    }

我试过这样做:

TableColumn tblclmnPayed = new TableColumn(membersTable, SWT.CENTER);

但它似乎只将列的标题居中,而不是内容。

Java SWT 可以满足我的需求吗?

【问题讨论】:

    标签: java eclipse swt windowbuilder


    【解决方案1】:

    为了使列的内容居中,您还需要为TableItem 指定SWT.CENTER 样式位。

    例如:

    final Table table = new Table(shell, SWT.BORDER | SWT.V_SCROLL | SWT.FULL_SELECTION);
    table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    table.setHeaderVisible(true);
    table.setLinesVisible(true);
    
    final TableColumn column1 = new TableColumn(table, SWT.NONE);
    column1.setText("Column 1");
    column1.setWidth(75);
    
    final TableColumn column2 = new TableColumn(table, SWT.NONE);
    column2.setText("Column 2");
    column2.setWidth(75);
    
    final TableColumn column3 = new TableColumn(table, SWT.CENTER);
    column3.setText("Column 3");
    column3.setWidth(75);
    
    for (int i = 0; i < 5; i++) {
        new TableItem(table, SWT.CENTER).setText(new String[] { "a", "b", "c" });
    }
    

    请注意,这只会影响同时指定SWT.CENTER 的列的内容,而不影响其他列的内容。


    编辑关于图像居中:

    我不相信可以通过样式位在表格行中居中放置图像,因为它们似乎被忽略了。

    另一种方法是使用绘图侦听器绘制具有正确填充的图像,以使图像在列中居中(请参阅:How to align image to center of table cell (SWT Table))。请注意,使用此方法不会根据图像的大小调整行的大小,因此除非您的图像很小/与行的高度相同,否则您必须做一些额外的工作以保持图像形式被切断。

    【讨论】:

    • 没用。也许是因为内容是图像?我编辑了我的帖子,添加了我添加图像的代码
    • @NullPointerException 我不确定是否可以使用样式位在行内居中图像 - 我添加了一个编辑,其中包含可能适用于您的情况的替代方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2016-05-11
    • 1970-01-01
    • 2010-11-18
    • 2020-04-10
    • 2019-02-18
    相关资源
    最近更新 更多