2011-08-19 43 views

回答

18

你可以覆蓋JButton實例的paintComponent方法和與實施Paint接口下面類中的一個繪製其Graphics對象:


import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.FlowLayout; 
import java.awt.GradientPaint; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Point; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.SwingUtilities; 

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 class JGradientButton extends JButton { 
     private JGradientButton() { 
      super("Gradient Button"); 
      setContentAreaFilled(false); 
      setFocusPainted(false); // used for demonstration 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      final 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 JGradientButton newInstance() { 
      return new JGradientButton(); 
     } 
    } 
} 

enter image description here

+1

因爲應該是L&F敏感,但合租不錯+1 – mKorbel

+1

我已經對SO –

5

在麥格理的回答有點起色:

enter image description here

private static final class JGradientButton extends JButton{ 
    private JGradientButton(String text){ 
     super(text); 
     setContentAreaFilled(false); 
    } 

    @Override 
    protected void paintComponent(Graphics g){ 
     Graphics2D g2 = (Graphics2D)g.create(); 
     g2.setPaint(new GradientPaint(
       new Point(0, 0), 
       getBackground(), 
       new Point(0, getHeight()/3), 
       Color.WHITE)); 
     g2.fillRect(0, 0, getWidth(), getHeight()/3); 
     g2.setPaint(new GradientPaint(
       new Point(0, getHeight()/3), 
       Color.WHITE, 
       new Point(0, getHeight()), 
       getBackground())); 
     g2.fillRect(0, getHeight()/3, getWidth(), getHeight()); 
     g2.dispose(); 

     super.paintComponent(g); 
    } 
} 
+0

找到最好的解決辦法一個將如何實現這一個按鈕,已經是一個圖形用戶界面的一部分?如果我將其添加到按鈕,我是否需要更改動作偵聽器?那可能嗎?或者,更好的問題;首先要問一個合理的問題? –

+0

如果一個GUI已經有一個按鈕,必須有一些代碼來創建該按鈕(JButton b = new JButton(「whatever」))。要替換默認按鈕,您需要改爲創建一個JGradientButton(JButton b = new JGradientButton(「whatever」))並將背景顏色設置爲您喜歡的(b.setBackground(.. somecolor ...))。 GUI中處理按鈕的其餘代碼應保持不變 – luca

相關問題