Set the cell width to 3 tables

I have 3 tables in the same form, but they are different. columns, and I want to set the column width for each of the tables. Can I get this in the code below or do I need to create 3 different classes extending the table and then set a different constraint width? In doing so, I write the same code three times, which I do not want to do.

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;
  }
}
+4
source share
1 answer

If you want all the columns to be the same in width, you can do something like:

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());
   ...
 }

Otherwise, you can just go with the new constructor to a string:

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

Then you can just do it in createCell:

constraint.setWidthPercentage(widths[column]);
+1
source

Source: https://habr.com/ru/post/1622523/


All Articles