我的按钮有文字和图标。如果用户调整框架大小并使按钮不可见,我想隐藏文本。我找到了滚动窗格的解决方法,但我想知道是否有更好的解决方案。提前谢谢。
我的解决方案:
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("");
}
}
});
}
}
}
我向JPanel
添加了按钮,并使用滚动窗格将该面板添加到框架中。在ResizeListener
我正在检查水平滚动是否可见。如果它可见,则表示buttonPanel
溢出可见区域。
答案 0 :(得分:1)
我找到了滚动窗格的解决方法,但我想知道是否有更好的解决方案。
不知道它是否更好,但不需要滚动窗格。只需将侦听器添加到面板,然后您可以根据实际宽度检查首选宽度:
button1.setText("Button1");
button2.setText("Button2");
button3.setText("Button2");
JPanel panel = (JPanel)e.getComponent();
if (panel.getSize().width < panel.getPreferredSize().width)
{
button1.setText("");
button2.setText("");
button3.setText("");
}
如果用户调整框架大小并使按钮不可见,我想要隐藏文本。
如果您只是想确保所有按钮都可以访问,那么您可以:
使用Wrap Layout。按钮将换行换行,面板的高度将增加。
使用ScrollContainer的概念。按钮将根据需要添加到容器的开头/结尾,以允许您滚动当前不可见的按钮。请参阅:Moving left right in a JPanel