Luk*_*til 0 java swing jbutton
我想将两个或多个图标设置为一个 JButton(Java,Swing)。是否可以?
我添加了绘图中制作的图片。;-)
实现此目的的最佳方法是创建一个实现该Icon
界面的自定义类,该类只需并排绘制两个给定的图标即可。
public class TwoIcon implements Icon {
private final int iconGap = 2;
private final Icon icon1;
private final Icon icon2;
public TwoIcon(final Icon icon1, final Icon icon2) {
this.icon1 = icon1;
this.icon2 = icon2;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
int mid = getIconHeight() / 2;
int y1 = y + mid - icon1.getIconHeight() / 2;
int y2 = y + mid - icon2.getIconHeight() / 2;
icon1.paintIcon(c, g, x, y1);
icon2.paintIcon(c, g, x + icon1.getIconWidth() + iconGap, y2);
}
@Override
public int getIconWidth() {
return icon1.getIconWidth() + icon2.getIconWidth() + iconGap;
}
@Override
public int getIconHeight() {
return Math.max(icon1.getIconHeight(), icon2.getIconHeight());
}
}
Run Code Online (Sandbox Code Playgroud)
图标将并排绘制,填充为2
且垂直居中。如果您希望它们以不同的方式对齐,请调整间距。
Icon leftIcon = ...
Icon rightIcon = ...
button.setIcon(new TwoIcon(leftIcon, rightIcon));
Run Code Online (Sandbox Code Playgroud)
结果:我只是使用在这里绘制纯色的图标。16x16
一个的大小是20x20
为了演示垂直对齐。
事实上,这并不限于JButton
并且适用于任何JComponent
可以使用图标(例如JLabel
等)的人。
归档时间: |
|
查看次数: |
508 次 |
最近记录: |