java – 设置3个表的不同单元格宽度

我有3张相同形式的表,但它们有不同的号码.列我想为每个表设置不同的列宽.我可以在下面的代码中获得它,或者我必须创建3个不同的类扩展表,然后设置不同的约束宽度?通过这样做,我写了三次相同的代码,我不想这样做.

protected void beforeReport(Form f){
  Table table=new MyTable(new DefaultTableModel(columnNamesInOut,dataInOut));
  Table tablePunishment=new MyTable(new DefaultTableModel(columnNamesPunishment,dataPunishment));
  Table tableAccident=new MyTable(new DefaultTableModel(columnNamesAccident,dataAccident));
}

public class MyTable extends Table {

  public MyTable(TableModel tm) {
    super(tm, true);
  }

  public Component createCell(Object value, int row, int col, boolean editable) {
    Component component = null;
    if (value instanceof Vector) {
      Container c = new Container(new BoxLayout(BoxLayout.Y_AXIS));
      Iterator i = ((Vector) value).iterator();
      while (i.hasNext()) {
        c.addComponent(new Label(i.next().toString()));
      }
      component = c;
    } else {
      component = super.createCell(value, row, col, editable);
    }
    return component;
  }

  @Override
  protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) {
    TableLayout.Constraint constraint = ((TableLayout) this.getLayout()).createConstraint();
    constraint.setVerticalAlign(CENTER);
    addComponent(constraint);

    switch (column) {
      case 0: {
        constraint.setWidthPercentage(25);
        break;
      }
      case 1: {
        constraint.setWidthPercentage(25);
        break;
      }
      case 2: {
        constraint.setWidthPercentage(25);
        break;
      }
      case 3: {
        constraint.setWidthPercentage(25);
        break;
      }
    }
    return constraint;
  }
}

最佳答案 如果您希望所有列的宽度相同,您可以执行以下操作:

protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) {
   TableLayout.Constraint constraint = ((TableLayout) this.getLayout()).createConstraint();
   constraint.setVerticalAlign(CENTER);
   addComponent(constraint);
   constraint.setWidthPercentage(100 / getModel().getColumnCount());
   ...
 }

否则你可以使用以下行中的新构造函数:

public class MyTable extends Table {
  private int[] widths;
  public MyTable(TableModel tm, int... widths) {
    super(tm, true);
    this.widths = widths;
  }

然后你可以在createCell中执行此操作:

constraint.setWidthPercentage(widths[column]);
点赞