【发布时间】:2017-02-17 14:52:44
【问题描述】:
所以我有一个JButton,当您将鼠标移到它上面时,会出现一个使用 HTML 的下划线。然而,当添加下划线时,它会使JButton 比它应该的要大一点。
我尝试了一些类似的方法
button.setMaximumSize(button.getPreferredSize());
在添加下划线之前,但我无法修复它。那么,无论是否存在下划线,我如何确保高度保持不变。
我在下面有一个示例类来演示问题(我无法让它具有完全相同的严重性,但足以显示问题)。
示例类
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.metal.MetalButtonUI;
public class UnderlineSample extends JFrame {
public UnderlineSample() {
super("Underline Sample");
setLayout(new GridBagLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(300, 150));
String text =
"<html>"
+ "<p style = 'border-bottom: 1px solid rgba(0,0,0,0,0); box-sizing: border-box;'>"
+ "<span style = 'color: rgb(0, 0, 255); font-weight: bold;'>"
+ "Sample"
+ "</span> "
+ " underline button"
+ "</p>"
+ "</html>";
JButton button = new JButton(text);
button.setFont(new Font("", Font.PLAIN, 18));
button.setFocusable(false);
button.setBackground(Color.LIGHT_GRAY);
button.setForeground(Color.BLACK);
button.setUI(new MetalButtonUI());
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setAlignmentX(LEFT_ALIGNMENT);
button.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
String s =
"<html>"
+ "<p style = 'border-bottom: 1px solid black; box-sizing: border-box;'>"
+ "<span style = 'color: rgb(0, 0, 255); font-weight: bold;'>"
+ "Sample"
+ "</span> "
+ " underline button"
+ "</p>"
+ "</html>";
button.setText(s);
}
public void mouseExited(MouseEvent e) {
String s =
"<html>"
+ "<p style = 'border-bottom: 1px solid rgba(0,0,0,0,0); box-sizing: border-box;'>"
+ "<span style = 'color: rgb(0, 0, 255); font-weight: bold;'>"
+ "Sample"
+ "</span> "
+ " underline button"
+ "</p>"
+ "</html>";
button.setText(s);
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.ipady = 10;
gbc.insets = new Insets(0, 10, 5, 10);
add(button, gbc);
pack();
setVisible(true);
}
public static void main(String[] args) {
new UnderlineSample();
}
}
【问题讨论】:
标签: java html jbutton preferredsize