Google Tag Manager

2008/03/26

JTable pagination using RowFilter

Code

public class MainPanel extends JPanel {
  private static final Color evenColor = new Color(240, 255, 250);
  private static final LinkViewRadioButtonUI ui = new LinkViewRadioButtonUI();
  private static int LR_PAGE_SIZE = 5;

  private final TestModel model = new TestModel();
  private final TableRowSorter< TestModel > sorter = new TableRowSorter< TestModel >(model);
  private final Box box = Box.createHorizontalBox();
  public MainPanel() {
    super(new BorderLayout());
    JTable table = new JTable(model) {
      @Override
      public Component prepareRenderer(TableCellRenderer tcr, int row, int column) {
        Component c = super.prepareRenderer(tcr, row, column);
        if(isRowSelected(row)) {
          c.setForeground(getSelectionForeground());
          c.setBackground(getSelectionBackground());
        }else{
          c.setForeground(getForeground());
          c.setBackground((row%2==0)?evenColor:getBackground());
        }
        return c;
      }
    };
    table.setFillsViewportHeight(true);
    table.setIntercellSpacing(new Dimension());
    table.setShowHorizontalLines(false);
    table.setShowVerticalLines(false);
    table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    table.setRowSorter(sorter);

    for(int i=0;i <= 2008;i++) {
      model.addTest(new Test(" Test: "+i, (i%2==0)?"":"comment..."));
    }
    initLinkBox(100, 1);

    add(box, BorderLayout.NORTH);
    add(new JScrollPane(table));
    setPreferredSize(new Dimension(320, 240));
  }
  private void initLinkBox(final int itemsPerPage, final int currentPageIndex) {
    //assert currentPageIndex > 0;
    sorter.setRowFilter(makeRowFilter(itemsPerPage, currentPageIndex-1));

    ArrayList< JRadioButton > l = new ArrayList< JRadioButton >();

    int startPageIndex = currentPageIndex-LR_PAGE_SIZE;
    if(startPageIndex <= 0) startPageIndex = 1;

//#if 0
    //int maxPageIndex = (model.getRowCount()/itemsPerPage)+1;
//#else
    /* "maxPageIndex" gives one blank page if the module of the division is not zero.
     *   pointed out by erServi
     * e.g. rowCount=100, maxPageIndex=100
     */
    int rowCount = model.getRowCount();
    int maxPageIndex = (rowCount/itemsPerPage) + (rowCount%itemsPerPage==0?0:1);
//#endif
    int endPageIndex = currentPageIndex+LR_PAGE_SIZE-1;
    if(endPageIndex>maxPageIndex) endPageIndex = maxPageIndex;

    if(currentPageIndex > 1)
        l.add(makePNRadioButton(itemsPerPage, currentPageIndex-1, "Prev"));
    //for(int i=startPageIndex;i <= endPageIndex;i++) 
    //    l.add(makeRadioButton(itemsPerPage, currentPageIndex, i-1));
    //if I only have one page, Y don't want to see pagination buttons
    //suggested by erServi
    if(startPageIndex < endPageIndex) {
      for(int i=startPageIndex; i<= endPageIndex;i++) {
          l.add(makeRadioButton(itemsPerPage, currentPageIndex, i-1));
      }
    }
    if(currentPageIndex < maxPageIndex)
        l.add(makePNRadioButton(itemsPerPage, currentPageIndex+1, "Next"));

    box.removeAll();
    ButtonGroup bg = new ButtonGroup();
    box.add(Box.createHorizontalGlue());
    for(JRadioButton r:l) {
      box.add(r); bg.add(r);
    }
    box.add(Box.createHorizontalGlue());
    box.revalidate();
    box.repaint();
    l.clear();
  }

  private JRadioButton makeRadioButton(final int itemsPerPage,
                                       final int current, final int target) {
    JRadioButton radio = new JRadioButton(""+(target+1));
    radio.setForeground(Color.BLUE);
    radio.setUI(ui);
    if(target+1==current) {
      radio.setSelected(true);
      radio.setForeground(Color.BLACK);
    }
    radio.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        initLinkBox(itemsPerPage, target+1);
      }
    });
    return radio;
  }
  private JRadioButton makePNRadioButton(final int itemsPerPage, final int target, String title) {
    JRadioButton radio = new JRadioButton(title);
    radio.setForeground(Color.BLUE);
    radio.setUI(ui);
    radio.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        initLinkBox(itemsPerPage, target);
      }
    });
    return radio;
  }

  private RowFilter< TestModel, Integer > makeRowFilter(final int itemsPerPage, final int target) {
    return new RowFilter< TestModel, Integer >() {
      @Override
      public boolean include(Entry< ? extends TestModel, ? extends Integer > entry) {
        int ei = entry.getIdentifier();
        return (target*itemsPerPage <= ei && ei < target*itemsPerPage+itemsPerPage);
      }
    };
  }

  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        createAndShowGUI();
      }
    });
  }

  public static void createAndShowGUI() {
    try{
      UIManager.getInstalledLookAndFeels();
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }catch(Exception e) {
      e.printStackTrace();
    }
    final JFrame frame = new JFrame("@title@");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(new MainPanel());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}

References

2008/03/21

Horizontally fill tabs of a JTabbedPane

Code

//horizontal filling, same width tabs
class ClippedTitleTabbedPane extends JTabbedPane {
  public ClippedTitleTabbedPane() {
    super();
  }
  public ClippedTitleTabbedPane(int tabPlacement) {
    super(tabPlacement);
  }
  private Insets getTabInsets() {
    Insets i = UIManager.getInsets("TabbedPane.tabInsets");
    if(i!=null) {
      return i;
    }else{
      SynthStyle style = SynthLookAndFeel.getStyle(
        this, Region.TABBED_PANE_TAB);
      SynthContext context = new SynthContext(
        this, Region.TABBED_PANE_TAB, style, SynthConstants.ENABLED);
      return style.getInsets(context, null);
    }
  }
  private Insets getTabAreaInsets() {
    Insets i = UIManager.getInsets("TabbedPane.tabAreaInsets");
    if(i!=null) {
      return i;
    }else{
      SynthStyle style = SynthLookAndFeel.getStyle(
        this, Region.TABBED_PANE_TAB_AREA);
      SynthContext context = new SynthContext(
        this, Region.TABBED_PANE_TAB_AREA, style, SynthConstants.ENABLED);
      return style.getInsets(context, null);
    }
  }
  @Override public void doLayout() {
    int tabCount  = getTabCount();
    if(tabCount==0) return;
    Insets tabInsets   = getTabInsets();
    Insets tabAreaInsets = getTabAreaInsets();
    Insets insets = getInsets();
    int areaWidth = getWidth() - tabAreaInsets.left - tabAreaInsets.right
                               - insets.left        - insets.right;
    int tabWidth  = 0; // = tabInsets.left + tabInsets.right + 3;
    int gap     = 0;

    switch(getTabPlacement()) {
      case LEFT: case RIGHT:
      tabWidth = areaWidth / 4;
      gap = 0;
      break;
      case BOTTOM: case TOP: default:
      tabWidth = areaWidth / tabCount;
      gap = areaWidth - (tabWidth * tabCount);
    }
    // "3" is magic number @see BasicTabbedPaneUI#calculateTabWidth
    tabWidth = tabWidth - tabInsets.left - tabInsets.right - 3;
    for(int i=0;i < tabCount;i++) {
      JLabel l = (JLabel)getTabComponentAt(i);
      if(l==null) break;
      l.setPreferredSize(new Dimension(
          tabWidth+(i < gap?1:0), l.getPreferredSize().height));
    }
    super.doLayout();
  }
  @Override
  public void insertTab(
      String title, Icon icon, Component component,
      String tip, int index) {
    super.insertTab(title, icon, component,
                    tip==null?title:tip, index);
    JLabel label = new JLabel(title, JLabel.CENTER);
    Dimension dim = label.getPreferredSize();
    Insets tabInsets = getTabInsets();
    label.setPreferredSize(new Dimension(
      0, dim.height+tabInsets.top+tabInsets.bottom));
    setTabComponentAt(index, label);
  }
}

References

2008/03/18

JProgressBar in JTable Cell

Code

class ProgressRenderer extends DefaultTableCellRenderer {
  private final JProgressBar b = new JProgressBar(0, 100);
  public ProgressRenderer() {
    super();
    setOpaque(true);
    b.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
  }
  public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {
    Integer i = (Integer) value;
    String text = "Done";
    if (i < 0) {
      text = "Canceled";
    } else if (i < 100) {
      b.setValue(i);
      return b;
    }
    super.getTableCellRendererComponent(table, text, isSelected, hasFocus, row, column);
    return this;
  }
}
final Executor executor = Executors.newCachedThreadPool();
final int rowNumber = model.getRowCount();
SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
  private int sleepDummy = new Random().nextInt(100) + 1;
  private int lengthOfTask = 120;
  @Override
  protected Integer doInBackground() {
    int current = 0;
    while (current < lengthOfTask && !isCancelled()) {
      if (!table.isDisplayable()) {
        return -1;
      }
      current++;
      try {
        Thread.sleep(sleepDummy);
      } catch (InterruptedException ie) {
        publish(-1);
        break;
      }
      publish(100 * current / lengthOfTask);
    }
    return sleepDummy * lengthOfTask;
  }
  @Override
  protected void process(List<Integer> chunks) {
    for (Integer value : chunks) {
      model.setValueAt(value, rowNumber, 2);
    }
    // model.fireTableCellUpdated(rowNumber, 2);
  }
  @Override
  protected void done() {
    String text;
    int i = -1;
    if (isCancelled()) {
      text = "Canceled";
    } else {
      try {
        i = get();
        text = (i>=0)?"Done":"Disposed";
      } catch (Exception ignore) {
        ignore.printStackTrace();
        text = ignore.getMessage();
      }
    }
    System.out.println(rowNumber +":"+text+"("+i+"ms)");
  }
};
model.addTest(new Test("example", 0), worker);
executor.execute(worker); // JDK 1.6.0_18
// worker.execute();

References