[英]Java Swing keep the button look&feel but background color
我想更改Java Swing JButton的背景顏色。
原始按鈕如下所示:
更改此按鈕的背景顏色后,它看起來像這樣:
原始的具有“按鈕”外觀和感覺。 但是,黃色的背景看起來像是黃色的普通背景,頂部帶有一些文本。
問題:有什么簡便的方法可以更改此特定Jbutton的背景顏色,但保持外觀?
附言:我知道我可以制作圖像並將其附加到按鈕上。 但是,按鈕的尺寸不會總是相同的,因此圖像可能不是一個好主意。 還有什么其他方法可以簡單地添加一些代碼, 例如添加一些邊框,邊距等 ,使其具有更多的按鈕感覺?
更新:
更改背景顏色后,我希望按鈕看起來像一個按鈕。 是否需要添加漸變背景或執行其他操作並不重要。 我正在尋找一種最簡單的方法。
您可以將GradientPaint
作為背景。
public final class JGradientButtonDemo {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame("Gradient JButton Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
frame.add(JGradientButton.newInstance());
frame.setSize(new Dimension(300, 150)); // used for demonstration
//frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static final class JGradientButton extends JButton{
private JGradientButton(){
super("Gradient Button");
setContentAreaFilled(false);
setFocusPainted(false); // used for demonstration
}
@Override
protected void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g.create();
g2.setPaint(new GradientPaint(
new Point(0, 0),
Color.WHITE,
new Point(0, getHeight()),
Color.PINK.darker()));
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
super.paintComponent(g);
}
public static final JGradientButton newInstance(){
return new JGradientButton();
}
}
}
使用這種外部api.Simply放線
UIManager.setLookAndFeel( “com.jtattoo.plaf.aluminium.AluminiumLookAndFeel”);
作為主要方法的第一行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.