Google Tag Manager

Showing posts with label JViewport. Show all posts
Showing posts with label JViewport. Show all posts

2015/09/30

aterai

Adjust the height of every row in the JTable to fit the JViewport

Code

JTable table = new JTable(model) {
  int prevHeight = -1;
  int prevCount = -1;
  public void updateRowsHeigth(JViewport vport) {
    int height = vport.getExtentSize().height;
    int rowCount = getModel().getRowCount();
    int defautlRowHeight = height / rowCount;
    if ((height != prevHeight || rowCount != prevCount) && defautlRowHeight > 0) {
      int over = height - rowCount * defautlRowHeight;
      for (int i = 0; i < rowCount; i++) {
        int a = over-- > 0 ? i == rowCount - 1 ? over : 1 : 0;
        setRowHeight(i, defautlRowHeight + a);
      }
    }
    prevHeight = height;
    prevCount = rowCount;
  }
  @Override public void doLayout() {
    super.doLayout();
    Container p = SwingUtilities.getAncestorOfClass(JViewport.class, this);
    if (p instanceof JViewport) {
      updateRowsHeigth((JViewport) p);
    }
  }
};

References

2015/03/30

aterai

Create a translucent JScrollBar

Code

public JComponent makeTranslucentScrollBar(JComponent c) {
  JScrollPane scrollPane = new JScrollPane(c) {
    @Override public boolean isOptimizedDrawingEnabled() {
      return false; // JScrollBar is overlap
    }
  };
  scrollPane.setVerticalScrollBarPolicy(
      ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
  scrollPane.setHorizontalScrollBarPolicy(
      ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

  scrollPane.setComponentZOrder(scrollPane.getVerticalScrollBar(), 0);
  scrollPane.setComponentZOrder(scrollPane.getViewport(), 1);
  scrollPane.getVerticalScrollBar().setOpaque(false);

  scrollPane.setLayout(new ScrollPaneLayout() {
    @Override public void layoutContainer(Container parent) {
      JScrollPane scrollPane = (JScrollPane) parent;

      Rectangle availR = scrollPane.getBounds();
      availR.x = availR.y = 0;

      Insets insets = parent.getInsets();
      availR.x = insets.left;
      availR.y = insets.top;
      availR.width  -= insets.left + insets.right;
      availR.height -= insets.top  + insets.bottom;

      Rectangle vsbR = new Rectangle();
      vsbR.width  = 12;
      vsbR.height = availR.height;
      vsbR.x = availR.x + availR.width - vsbR.width;
      vsbR.y = availR.y;

      if (viewport != null) {
        viewport.setBounds(availR);
      }
      if (vsb != null) {
        vsb.setVisible(true);
        vsb.setBounds(vsbR);
      }
    }
  });
  scrollPane.getVerticalScrollBar().setUI(new BasicScrollBarUI() {
    private final Color defaultColor  = new Color(220, 100, 100, 100);
    private final Color draggingColor = new Color(200, 100, 100, 100);
    private final Color rolloverColor = new Color(255, 120, 100, 100);
    private final Dimension d = new Dimension();
    @Override protected JButton createDecreaseButton(int orientation) {
      return new JButton() {
        @Override public Dimension getPreferredSize() {
          return d;
        }
      };
    }
    @Override protected JButton createIncreaseButton(int orientation) {
      return new JButton() {
        @Override public Dimension getPreferredSize() {
          return d;
        }
      };
    }
    @Override protected void paintTrack(Graphics g, JComponent c, Rectangle r) {}
    @Override protected void paintThumb(Graphics g, JComponent c, Rectangle r) {
      Color color;
      JScrollBar sb = (JScrollBar) c;
      if (!sb.isEnabled() || r.width > r.height) {
        return;
      } else if (isDragging) {
        color = draggingColor;
      } else if (isThumbRollover()) {
        color = rolloverColor;
      } else {
        color = defaultColor;
      }
      Graphics2D g2 = (Graphics2D) g.create();
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                          RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setPaint(color);
      g2.fillRect(r.x, r.y, r.width - 1, r.height - 1);
      g2.setPaint(Color.WHITE);
      g2.drawRect(r.x, r.y, r.width - 1, r.height - 1);
      g2.dispose();
    }
    @Override protected void setThumbBounds(int x, int y, int width, int height) {
      super.setThumbBounds(x, y, width, height);
      //scrollbar.repaint(x, 0, width, scrollbar.getHeight());
      scrollbar.repaint();
    }
  });
  return scrollPane;
}

References

2013/01/28

aterai

JScrollBar search highlighter

Code

Override WindowsScrollBarUI#paintTrack(...)

scrollbar.setUI(new WindowsScrollBarUI() {
  @Override protected void paintTrack(
      Graphics g, JComponent c, Rectangle trackBounds) {
    super.paintTrack(g, c, trackBounds);

    Rectangle rect = textArea.getBounds();
    double sy = trackBounds.getHeight() / rect.getHeight();
    AffineTransform at = AffineTransform.getScaleInstance(1.0, sy);
    Highlighter highlighter = textArea.getHighlighter();
    g.setColor(Color.YELLOW);
    try{
      for(Highlighter.Highlight hh: highlighter.getHighlights()) {
        Rectangle r = textArea.modelToView(hh.getStartOffset());
        Rectangle s = at.createTransformedShape(r).getBounds();
        int h = 2; //Math.max(2, s.height-2);
        g.fillRect(trackBounds.x, trackBounds.y+s.y, trackBounds.width, h);
      }
    }catch(BadLocationException e) {
      e.printStackTrace();
    }
  }
});

JLabel + Icon + RowHeader

final JScrollPane scroll = new JScrollPane(textArea);
JLabel label = new JLabel(new Icon() {
  private final Color THUMB_COLOR = new Color(0,0,255,50);
  private final Rectangle thumbRect = new Rectangle();
  private final JTextComponent textArea;
  private final JScrollBar scrollbar;
  public HighlightIcon(JTextComponent textArea, JScrollBar scrollbar) {
    this.textArea  = textArea;
    this.scrollbar = scrollbar;
  }
  @Override public void paintIcon(Component c, Graphics g, int x, int y) {
    //Rectangle rect   = textArea.getBounds();
    //Dimension sbSize = scrollbar.getSize();
    //Insets sbInsets  = scrollbar.getInsets();
    //double sy = (sbSize.height-sbInsets.top-sbInsets.bottom)/rect.getHeight();
    int itop = scrollbar.getInsets().top;
    BoundedRangeModel range = scrollbar.getModel();
    double sy = range.getExtent()/(double)(range.getMaximum()-range.getMinimum());
    AffineTransform at = AffineTransform.getScaleInstance(1.0, sy);
    Highlighter highlighter = textArea.getHighlighter();

    //paint Highlight
    g.setColor(Color.RED);
    try{
      for(Highlighter.Highlight hh: highlighter.getHighlights()) {
        Rectangle r = textArea.modelToView(hh.getStartOffset());
        Rectangle s = at.createTransformedShape(r).getBounds();
        int h = 2; //Math.max(2, s.height-2);
        g.fillRect(x, y+itop+s.y, getIconWidth(), h);
      }
    }catch(BadLocationException e) {
      e.printStackTrace();
    }

    //paint Thumb
    if(scrollbar.isVisible()) {
      //JViewport vport = Objects.requireNonNull(
      //  (JViewport)SwingUtilities.getAncestorOfClass(JViewport.class, textArea));
      //Rectangle thumbRect = vport.getBounds();
      thumbRect.height = range.getExtent();
      thumbRect.y = range.getValue(); //vport.getViewPosition().y;
      g.setColor(THUMB_COLOR);
      Rectangle s = at.createTransformedShape(thumbRect).getBounds();
      g.fillRect(x, y+itop+s.y, getIconWidth(), s.height);
    }
  }
  @Override public int getIconWidth() {
    return 8;
  }
  @Override public int getIconHeight() {
    JViewport vport = Objects.requireNonNull(
        (JViewport)SwingUtilities.getAncestorOfClass(JViewport.class, textArea));
    return vport.getHeight();
  }
});

scroll.setVerticalScrollBar(scrollbar);
/*
// Fixed Versions: 7 (b134)
scroll.setRowHeaderView(label);
/*/
// [JDK-6826074] JScrollPane does not revalidate the component hierarchy after scrolling - Java Bug System
// https://bugs.openjdk.java.net/browse/JDK-6826074
// Affected Versions: 6u12,6u16,7
JViewport vp = new JViewport() {
  @Override public void setViewPosition(Point p) {
    super.setViewPosition(p);
    revalidate();
  }
};
vp.setView(label);
scroll.setRowHeader(vp);

MatteBorder + Icon + RowHeader

JScrollBar scrollBar = new JScrollBar(JScrollBar.VERTICAL) {
  @Override public Dimension getPreferredSize() {
    Dimension d = super.getPreferredSize();
    d.width += getInsets().left;
    return d;
  }
  @Override public void updateUI() {
    super.updateUI();
    setBorder(BorderFactory.createMatteBorder(0, 4, 0, 0, new Icon() {
      @Override public void paintIcon(Component c, Graphics g, int x, int y) {
        //...
      }
      @Override public int getIconWidth() {
        return getInsets().left;
      }
      @Override public int getIconHeight() {
        return getHeight();
      }
    }));
  }
};
scroll.setVerticalScrollBar(scrollBar);

References

2012/06/21

aterai

Height of JTableHeader

Code

JScrollPane scroll = new JScrollPane(table);
scroll.setColumnHeader(new JViewport() {
  @Override public Dimension getPreferredSize() {
    Dimension d = super.getPreferredSize();
    d.height = 32;
    return d;
  }
});
//or
table.setTableHeader(new JTableHeader(table.getColumnModel()) {
  @Override public Dimension getPreferredSize() {
    Dimension d = super.getPreferredSize();
    d.height = 32;
    return d;
  }
});

References

2011/04/19

aterai

Transparent JTableHeader

Code

class TransparentHeader extends JLabel implements TableCellRenderer {
  private final Border b = BorderFactory.createCompoundBorder(
      BorderFactory.createMatteBorder(0,0,1,0,Color.BLACK),
      BorderFactory.createEmptyBorder(2,2,1,2));
  private final Color alphaZero = new Color(0, true);
  @Override public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected,
        boolean hasFocus, int row, int column) {
    this.setText(value!=null?value.toString():"");
    this.setHorizontalAlignment(JLabel.CENTER);
    this.setOpaque(false);
    this.setBackground(alphaZero);
    this.setForeground(Color.BLACK);
    this.setBorder(b);
    return this;
  }
}

References

2010/08/16

aterai

Kinetic Scrolling JScrollPane

Code

class KineticScrollingListener2 extends MouseAdapter {
  private static final int SPEED = 4;
  private static final int DELAY = 10;
  private static final double D = 0.8;
  private final Cursor dc;
  private final Cursor hc = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
  private final javax.swing.Timer inside;
  private final javax.swing.Timer outside;
  private final JComponent label;
  private Point startPt = new Point();
  private Point delta   = new Point();
  private static boolean isInside(JViewport vport, JComponent comp) {
    Point vp = vport.getViewPosition();
    return (vp.x>=0 && vp.x+vport.getWidth()-comp.getWidth()<=0 &&
            vp.y>=0 && vp.y+vport.getHeight()-comp.getHeight()<=0);
  }
  public KineticScrollingListener2(JComponent comp) {
    this.label = comp;
    this.dc = comp.getCursor();
    this.inside = new javax.swing.Timer(DELAY, new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        JViewport vport = (JViewport)label.getParent();
        Point vp = vport.getViewPosition();
        //System.out.format("s: %s, %s\n", delta, vp);
        vp.translate(-delta.x, -delta.y);
        vport.setViewPosition(vp);

        if (Math.abs(delta.x)>0 || Math.abs(delta.y)>0) {
          delta.setLocation((int)(delta.x*D), (int)(delta.y*D));
          //Outside
          if (vp.x<0 || vp.x+vport.getWidth()-label.getWidth()>0  )
            delta.x = (int)(delta.x*D);
          if (vp.y<0 || vp.y+vport.getHeight()-label.getHeight()>0)
            delta.y = (int)(delta.y*D);
        } else {
          inside.stop();
          if (!isInside(vport, label)) outside.start();
        }
      }
    });
    this.outside = new javax.swing.Timer(DELAY, new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        JViewport vport = (JViewport)label.getParent();
        Point vp = vport.getViewPosition();
        //System.out.format("r: %s\n", vp);
        if (vp.x<0) vp.x = (int)(vp.x*D);
        if (vp.y<0) vp.y = (int)(vp.y*D);
        if (vp.x+vport.getWidth()-label.getWidth()>0)
          vp.x=(int)(vp.x-(vp.x+vport.getWidth()-label.getWidth())*(1.0-D));
        if (vp.y+vport.getHeight()>label.getHeight())
          vp.y=(int)(vp.y-(vp.y+vport.getHeight()-label.getHeight())*(1.0-D));
        vport.setViewPosition(vp);
        if (isInside(vport, label)) outside.stop();
      }
    });
  }
  @Override public void mousePressed(MouseEvent e) {
    label.setCursor(hc);
    startPt.setLocation(e.getPoint());
    inside.stop();
    outside.stop();
  }
  @Override public void mouseDragged(MouseEvent e) {
    Point pt = e.getPoint();
    JViewport vport = (JViewport)label.getParent();
    Point vp = vport.getViewPosition();
    vp.translate(startPt.x-pt.x, startPt.y-pt.y);
    vport.setViewPosition(vp);
    delta.setLocation(SPEED*(pt.x-startPt.x), SPEED*(pt.y-startPt.y));
    startPt.setLocation(pt);
  }
  @Override public void mouseReleased(MouseEvent e) {
    label.setCursor(dc);
    if (isInside((JViewport)label.getParent(), label)) {
      inside.start();
    } else {
      outside.start();
    }
  }
}

References

2010/08/02

aterai

Transparent, Translucent JTable

Code

JScrollPane scroll = new JScrollPane(table) {
   private final TexturePaint texture = makeImageTexture();
  @Override protected JViewport createViewport() {
    return new JViewport() {
      @Override public void paintComponent(Graphics g) {
        if(texture!=null) {
          Graphics2D g2 = (Graphics2D)g;
          g2.setPaint(texture);
          g2.fillRect(0,0,getWidth(),getHeight());
        }
        super.paintComponent(g);
      }
    };
  }
};
final Color alphaZero = new Color(0, true);
table.setOpaque(false);
table.setBackground(alphaZero);
scroll.getViewport().setOpaque(false);
scroll.getViewport().setBackground(alphaZero);

References

2009/03/23

aterai

Mouse Dragging ViewPort Scroll

Code

//*
MouseAdapter hsl1 = new HandScrollListener();
vport.addMouseMotionListener(hsl1);
vport.addMouseListener(hsl1);
/*/
MouseAdapter hsl2 = new DragScrollListener();
label.addMouseMotionListener(hsl2);
label.addMouseListener(hsl2);
//*/
class HandScrollListener extends MouseInputAdapter {
  private final Cursor defCursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
  private final Cursor hndCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
  private final Point pp = new Point();
  @Override
  public void mouseDragged(final MouseEvent e) {
    Point cp = e.getPoint();
    Point vp = vport.getViewPosition();
    //= SwingUtilities.convertPoint(vport,0,0,label);
    vp.translate(pp.x-cp.x, pp.y-cp.y);
    if(r1.isSelected()) {
      label.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
    }else{
      vport.setViewPosition(vp);
    }
    pp.setLocation(cp);
  }
  @Override
  public void mousePressed(MouseEvent e) {
    label.setCursor(hndCursor);
    pp.setLocation(e.getPoint());
  }
  @Override
  public void mouseReleased(MouseEvent e) {
    label.setCursor(defCursor);
    label.repaint();
  }
}
class DragScrollListener extends MouseAdapter {
  private final Cursor defCursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
  private final Cursor hndCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
  private final Point pp = new Point();
  @Override public void mouseDragged(MouseEvent e) {
    final JComponent jc = (JComponent)e.getSource();
    Container c = jc.getParent();
    if(c instanceof JViewport) {
      JViewport vport = (JViewport)c;
      Point cp = SwingUtilities.convertPoint(jc,e.getPoint(),vport);
      Point vp = vport.getViewPosition();
      vp.translate(pp.x-cp.x, pp.y-cp.y);
      jc.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
      pp.setLocation(cp);
    }
  }
  @Override public void mousePressed(MouseEvent e) {
    JComponent jc = (JComponent)e.getSource();
    Container c = jc.getParent();
    if(c instanceof JViewport) {
      jc.setCursor(hndCursor);
      JViewport vport = (JViewport)c;
      Point cp = SwingUtilities.convertPoint(jc,e.getPoint(),vport);
      pp.setLocation(cp);
    }
  }
  @Override public void mouseReleased(MouseEvent e) {
    ((JComponent)e.getSource()).setCursor(defCursor);
  }
}

References

2008/06/25

aterai

Mouse Drag Auto Scrolling

Code

JLabel label = new JLabel();
//"CRW_3857_JFR.jpg" > http://sozai-free.com/
label.setIcon(new ImageIcon(getClass().getResource("CRW_3857_JFR.jpg")));
JScrollPane scroll = new JScrollPane(label,
    JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//*
ViewportDragScrollListener l = new ViewportDragScrollListener(label);
JViewport v = scroll.getViewport();
v.addMouseMotionListener(l);
v.addMouseListener(l);
v.addHierarchyListener(l);
/*/
//If label has its own MouseListeners, recommended to use ComponentDragScrollListener instead of ViewportDragScrollListener:
ComponentDragScrollListener l = new ComponentDragScrollListener(label);
label.addMouseMotionListener(l);
label.addMouseListener(l);
label.addHierarchyListener(l);
//*/
add(scroll);
scroll.setPreferredSize(new Dimension(320, 320));
class ViewportDragScrollListener extends MouseAdapter
                                 implements HierarchyListener {
  private static final int SPEED = 4;
  private static final int DELAY = 10;
  private final Cursor dc;
  private final Cursor hc = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
  private final javax.swing.Timer scroller;
  private final JComponent label;
  private Point startPt = new Point();
  private Point move    = new Point();

  public ViewportDragScrollListener(JComponent comp) {
    this.label = comp;
    this.dc = comp.getCursor();
    this.scroller = new javax.swing.Timer(DELAY, new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        JViewport vport = (JViewport)label.getParent();
        Point vp = vport.getViewPosition();
        vp.translate(move.x, move.y);
        label.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
      }
    });
  }
  @Override public void hierarchyChanged(HierarchyEvent e) {
    JComponent c = (JComponent)e.getSource();
    if((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED)!=0
       && !c.isDisplayable()) {
      scroller.stop();
    }
  }
  @Override public void mouseDragged(MouseEvent e) {
    JViewport vport = (JViewport)e.getSource();
    Point pt = e.getPoint();
    int dx = startPt.x - pt.x;
    int dy = startPt.y - pt.y;
    Point vp = vport.getViewPosition();
    vp.translate(dx, dy);
    label.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
    move.setLocation(SPEED*dx, SPEED*dy);
    startPt.setLocation(pt);
  }
  @Override public void mousePressed(MouseEvent e) {
    ((JComponent)e.getSource()).setCursor(hc); //label.setCursor(hc);
    startPt.setLocation(e.getPoint());
    move.setLocation(0, 0);
    scroller.stop();
  }
  @Override public void mouseReleased(MouseEvent e) {
    ((JComponent)e.getSource()).setCursor(dc); //label.setCursor(dc);
    scroller.start();
  }
  @Override public void mouseExited(MouseEvent e) {
    ((JComponent)e.getSource()).setCursor(dc); //label.setCursor(dc);
    move.setLocation(0, 0);
    scroller.stop();
  }
}
class ComponentDragScrollListener extends MouseAdapter
                                  implements HierarchyListener {
  private static final int SPEED = 4;
  private static final int DELAY = 10;
  private final Cursor dc;
  private final Cursor hc = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
  private final javax.swing.Timer scroller;
  private final JComponent label;
  private Point startPt = new Point();
  private Point move    = new Point();

  public ComponentDragScrollListener(JComponent comp) {
    this.label = comp;
    this.dc = comp.getCursor();
    this.scroller = new javax.swing.Timer(DELAY, new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        Container c = label.getParent();
        if(c instanceof JViewport) {
          JViewport vport = (JViewport)c;
          Point vp = vport.getViewPosition();
          vp.translate(move.x, move.y);
          label.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
        }
      }
    });
  }
  @Override public void hierarchyChanged(HierarchyEvent e) {
    JComponent jc = (JComponent)e.getSource();
    if((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED)!=0
       && !jc.isDisplayable()) {
      scroller.stop();
    }
  }
  @Override public void mouseDragged(MouseEvent e) {
    scroller.stop();
    JComponent jc = (JComponent)e.getSource();
    Container c = jc.getParent();
    if(c instanceof JViewport) {
      JViewport vport = (JViewport)jc.getParent();
      Point cp = SwingUtilities.convertPoint(jc,e.getPoint(),vport);
      int dx = startPt.x - cp.x;
      int dy = startPt.y - cp.y;
      Point vp = vport.getViewPosition();
      vp.translate(dx, dy);
      jc.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
      move.setLocation(SPEED*dx, SPEED*dy);
      startPt.setLocation(cp);
    }
  }
  @Override public void mousePressed(MouseEvent e) {
    scroller.stop();
    move.setLocation(0, 0);
    JComponent jc = (JComponent)e.getSource();
    jc.setCursor(hc);
    Container c = jc.getParent();
    if(c instanceof JViewport) {
      JViewport vport = (JViewport)c;
      Point cp = SwingUtilities.convertPoint(jc,e.getPoint(),vport);
      startPt.setLocation(cp);
    }
  }
  @Override public void mouseReleased(MouseEvent e) {
    ((JComponent)e.getSource()).setCursor(dc);
    scroller.start();
  }
  @Override public void mouseExited(MouseEvent e) {
    ((JComponent)e.getSource()).setCursor(dc);
    move.setLocation(0, 0);
    scroller.stop();
  }
}

References