I have both texts and icons for my buttons. I want to hide texts, if user resize the frame and make one the buttons invisible. I found a workaround with scroll pane, but I want to know if there is a better solution. Thanks in advance.
My solution:
public class IconButtonTest extends JFrame {
private JScrollPane buttonScrollPane;
private JButton button1;
private JButton button2;
private JButton button3;
public IconButtonTest() {
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
ImageIcon icon = new ImageIcon();
button1 = new JButton("Button1", icon);
button2 = new JButton("Button2", icon);
button3 = new JButton("Button2", icon);
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
buttonScrollPane = new JScrollPane(buttonPanel);
buttonScrollPane.setBorder(null);
add(buttonScrollPane, BorderLayout.NORTH);
addComponentListener(new ResizeListener());
setSize(300, 300);
setVisible(true);
}
public static void main(String[] args) {
new IconButtonTest();
}
private class ResizeListener extends ComponentAdapter {
@Override
public void componentResized(ComponentEvent e) {
button1.setText("Button1");
button2.setText("Button2");
button3.setText("Button2");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (buttonScrollPane.getHorizontalScrollBar().isVisible()) {
button1.setText("");
button2.setText("");
button3.setText("");
}
}
});
}
}
}
I added buttons to JPanel
and add that panel to the frame with a scroll pane. In ResizeListener
I am checking if horizontal scroll visible or not. If it is visible it means buttonPanel
is overflowed the visible area.