如何解决JButton添加的同尺寸图标向左偏移13像素的问题
问题原因
你同时为按钮设置了文本Reset和图标,Swing的JButton默认会预留文本显示的空间,且默认存在2~15px不等的内置边距、图标与文本的间距,所以会把图标向左挤压导致偏移。
可直接套用的修复方案
- 方案1:不需要显示按钮文本(纯图标按钮)
直接删除按钮初始化时的文本参数,同时清除按钮默认内边距、设置图标居中:private JButton getBtnReset() { if (btnReset == null) { // 移除文本参数,取消文本占位空间 btnReset = new JButton(); btnReset.setIcon(new ImageIcon(FrontEnd.class.getResource("/resources/Reset1.png"))); btnReset.setFont(new Font("OptimusPrinceps", Font.BOLD, 17)); btnReset.addActionListener(new BtnResetActionListener()); // 清除按钮默认上下左右内边距 btnReset.setMargin(new Insets(0, 0, 0, 0)); // 设置图标水平、垂直居中对齐 btnReset.setHorizontalAlignment(SwingConstants.CENTER); btnReset.setVerticalAlignment(SwingConstants.CENTER); btnReset.setBounds(400, 11, 167, 69); } return btnReset; } - 方案2:需要保留按钮文本
额外调整文本位置、图标与文本的间距即可:// 设置文本显示在图标正中间 btnReset.setHorizontalTextPosition(SwingConstants.CENTER); btnReset.setVerticalTextPosition(SwingConstants.CENTER); // 取消图标和文本的默认间距 btnReset.setIconTextGap(0);
内容的提问来源于stack exchange,提问作者Reewen
相关产品推荐
相关产品推荐

