Suppose you have a toolbar (of JPanel type) with so many icons embedded in it and when you resize your JFrame to a smaller size, not all the icons in your toolbar get displayed. What should you do? The solution I did was to add a left and right button as shown in the above toolbar image so that when you click either the left or right button, it will scroll sideways to display the next and/or previous icon of the toolbar (whichever button is pressed).

scrollabletoolbar

The toolbar container is placed within a scrollable pane while the scrollable pane is placed insider another JPanel class I created called ToolbarScroolablePanel wherein the left and right buttons are also added. I used a BorderLayout to place the toolbar in the center while the 2 buttons would be on the east and west position respectively.

If you look at the code closely, you may notice I used an Observer class called MyObserver. This is a pretty handy class for calling code found in other classes so you are spared the tedious task of calling deep level getParent() methods just to gain access to the container class. Now, this code only contains the panel class for the scrollable toolbar. When you use this class, just create an observer object in a static class and place it in the ToolbarScrollablePanel constructor which the syntax in the code means.

And in your JFrame class, you create a variable and instantiate the observer class like this:

Then from within the JFrame class, you add a ComponentListener and override the componentResized() method so that whenever the JFrame window gets resized, it will check if the toolbar’s visible area can or cannot display all toolbar icons to the screen which will be the basis to display the left and right buttons to scroll your toolbar icons.

Here are the source codes for both the ToolbarScrollablePanel and MyObserver class

Related Posts Plugin for WordPress, Blogger...