JScrollBar is displayed

Is there any way to know if it is visible JScrollBaror not inside JPanel?

I mean, several times my panel has a lot of rectangles (think of it like buttons), and you need a scroll bar, and sometimes it doesn’t need it. I would like to know if I can know when it will be shown.

+3
source share
4 answers

If you expand JPaneland add yourself JScrollbar(horizontal and / or vertical), then you can control when they should be visible or invisible
<(you can check if they are currently visible using the function isvisible())

, :

+3

, JScrollPane,

yourJScrollPane.getHorizontalScrollBar().isVisible()

yourJScrollPane.getVerticalScrollBar().isVisible()
+2

, :

final JScrollPane scroll = new JScrollPane(createMyPanel());
scroll.getVerticalScrollBar().addHierarchyListener(new HierarchyListener() {
  @Override
  public void hierarchyChanged(HierarchyEvent e) {
    if (e.getID() == HierarchyEvent.HIERARCHY_CHANGED && 
      (e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) {
      System.out.println(scroll.getVerticalScrollBar().isVisible());
    }
  }
});
+2

VonC Joshua, , isVisible() Component. , javadoc :

, , . , , Frame.

This means that until it JScrollPaneis added to the dimension frame, the call isVisible()to JScrollBarwill always be returned true.

Consider the following SSCCE:

public static void main(String[] args) {
  // creates a small table in a larger scroll pane
  int size = 5; 
  JTable table = new JTable(makeData(size), makeHeadings(size));
  JScrollPane pane = new JScrollPane(table);
  pane.setPreferredSize(new Dimension(200, 200));
  System.out.println(pane.getVerticalScrollBar().isVisible()); // prints true

  JFrame frame = new JFrame("JScrollPane Test");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setContentPane(pane);
  System.out.println(pane.getVerticalScrollBar().isVisible()); // prints true

  frame.pack();
  System.out.println(pane.getVerticalScrollBar().isVisible()); // prints false

  frame.setVisible(true);
  System.out.println(pane.getVerticalScrollBar().isVisible()); // prints false
}

private static Object[] makeHeadings(int size) {
  Object[] headings = new Object[size];
  for (int i=0; i<size; i++){
    headings[i] = i;
  }
  return headings;
}

private static Object[][] makeData(int size) {
  Object[][] data = new Object[size][size];
  for (int i=0; i<size; i++){
    for (int j=0; j<size; j++){
      data[i][j] = i*j;
    }
  }
  return data;
}

Similarly, it’s worth adding that if you add JScrollPaneto the inner frame, it scrollBar.isVisible()will work only after the inner frame has been added to another component.

+1
source

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


All Articles