如何根据JButton的大小自动增加或减少JButton文本的大小?
作者:互联网
我试图自动增加/减少JButton文本的字体大小(如果JButton增加/延伸其文本也将增加,如果JButton减少其文本也将减少). JButtons的默认字体是Sans-Serif大小为20,它永远不会减少到20以下(它可以是21,30,40或任何高于或等于20但不低于20的任何东西).我有一个名为MenuJPanel的JPanel,它使用GridLayout添加5个JButton,随着JPanel的增加/减少,这将增加/减少.我选择了GridLayout,因为它似乎是为此目的的最佳布局,我错了吗?我还在MenuJPanel中添加了一个componentResized.下面你可以看到我的代码部分工作.
public class MenuJPanel extends JPanel {
private JButton resizeBtn1;
private JButton resizeBtn2;
private JButton resizeBtn3;
private JButton resizeBtn4;
private JButton resizeBtn5;
public MenuJPanel() {
initComponents();
this.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
Font btnFont = resizeBtn1.getFont();
String btnText = resizeBtn1.getText();
int stringWidth = resizeBtn1.getFontMetrics(btnFont).stringWidth(btnText);
int componentWidth = resizeBtn1.getWidth();
// Find out how much the font can grow in width.
double widthRatio = (double) componentWidth / (double) stringWidth;
int newFontSize = (int) (btnFont.getSize() * widthRatio);
int componentHeight = resizeBtn1.getHeight();
// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, componentHeight);
// Set the label's font size to the newly determined size.
resizeBtn1.setFont(new Font(btnFont.getName(), Font.BOLD, fontSizeToUse));
}
});
}
private void initComponents() {
resizeBtn1 = new javax.swing.JButton();
resizeBtn2 = new javax.swing.JButton();
resizeBtn3 = new javax.swing.JButton();
resizeBtn4 = new javax.swing.JButton();
resizeBtn5 = new javax.swing.JButton();
setLayout(new java.awt.GridLayout(5, 0));
resizeBtn1.setText("Text to resize 1");
add(resizeBtn1);
resizeBtn2.setText("Text to resize 2");
add(resizeBtn2);
resizeBtn3.setText("Text to resize 3");
add(resizeBtn3);
resizeBtn4.setText("Text to resize 4");
add(resizeBtn4);
resizeBtn5.setText("Text to resize 5");
add(resizeBtn5);
}
}
解决方法:
通常,JButton的ButtonUI委托根据设计者选择的字体和平台的美学来计算按钮的首选大小.由于您的方法失败了,您可以决定文本如何使用按钮缩放并适应按钮装饰.
如果没有创建自己的ButtonUI,您可以简单地缩放文本.在这个example中,TextLayout用于以任意大的大小呈现BufferedImage中的文本,可以根据需要缩小.在此example中,单个数字的字形在BufferedImage中呈现并缩放以适合按钮的当前大小.如果需要处理Icon的相对位置,请参阅SwingUtilities.layoutCompoundLabel(),检查here.
标签:java,swing,jpanel,jbutton,grid-layout 来源: https://codeday.me/bug/20190520/1143989.html