![](/img/trans.png)
[英]how to stop JButton from changing position when a Jlabel is added before it
[英]How to stop a JButton's height from changing after adding an underline?
因此,我有一個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();
}
}
Swing中的html/css
渲染不支持所有CSS樣式。 關鍵點rgba
無法正常工作(您可以使用希望渲染的rgba
添加彩色邊框(而不是帶有alpha 0的邊框來查看結果)來自己進行測試)。
換句話說,不會渲染帶有rgba
的邊框,因此當您使用MouseListener.mouseEntered
添加可渲染的border-bottom時,尺寸會發生變化。 您可以使用與背景顏色相同的rgb
來欺騙它。 就像是:
<p style = 'border-bottom: 1px solid rgb(200,200,200); box-sizing: border-box;'>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.