2015-08-22 91 views
-1

如何在Swing中使用內部陰影創建一個像這樣的JButton如何在Swing中創建帶邊框陰影的JButton

enter image description here

我想新建JButton邊境的不同Color,像頂部和左邊框的顏色應該是黑色,右邊和底部邊框的顏色應該是白色。

但是,所有在一起,我想要像上面的圖像的頂部和左側的深灰色的內部陰影。

+2

這是一個「笑話問題」或什麼?因爲[鏈接](http://stackoverflow.com/a/32154944/4857909)。 –

+0

我刪除了我的答案,因爲它好像你自己回答了這個問題... –

+1

@LuxxMiner:請重新考慮;另請參閱此相關的[示例](http://stackoverflow.com/a/5755124/230513)。 – trashgod

回答

4

首先,我認爲你可以用一個簡單的BevelBorder來實現這一點,但不幸的是你不能設置邊界的厚度舒適...所以我不得不基本上做一個定製的Border。如果您不喜歡paintBorder方法中按鈕的樣式,但您必須知道如何使用Graphics,則可以對其進行更多定製。這是我得到的:

import java.awt.Color; 
import java.awt.Component; 
import java.awt.Dimension; 
import java.awt.FlowLayout; 
import java.awt.Graphics; 
import java.awt.Insets; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.border.Border; 

/** 
* 
*/ 
public class MyBorder implements Border { 

    private int thickness_ = 4; 
    private Color white = Color.WHITE; 
    private Color gray = Color.GRAY; 
    private Color black = Color.BLACK; 

    public static void main(String[] args) { 

     JFrame frm = new JFrame("Border Test"); 
     frm.setLayout(new FlowLayout()); 
     JButton btn = new JButton("Button"); 

     MyBorder border = new MyBorder(); 

     btn.setBorder(border); 
     btn.setFocusPainted(false); 
     btn.setPreferredSize(new Dimension(60,30)); 
     btn.setBackground(Color.LIGHT_GRAY); 

     frm.add(btn); 
     frm.setSize(200,200); 
     frm.setVisible(true); 

    } 

    public void paintBorder(Component c, Graphics g, int x, int y, int width, 
      int height) { 
     Color oldColor = g.getColor(); 
     int i; 

     for (i = 0; i < thickness_; i++) { 
      g.setColor(white); 
      g.drawRect(x + i, y + i, width - i - i - 1, height - i - i - 1); //White Rectangle 
     } 
     for (i = 0; i < thickness_/2; i++) { 
      g.setColor(black); 
      g.drawLine(x + i, y + i, (width - x) - (i * 2), y + i); //Top Outer Edge 
      g.drawLine(x + i, y + i, x + i, (height - y) - (i * 2)); //Left Outer Edge 
     } 
     for (i = thickness_/2; i < thickness_; i++) { 
      g.setColor(gray); 
      g.drawLine(x + i, y + i, (width - x) - (i * 2), y + i); //Top Inner Edge 
      g.drawLine(x + i, y + i, x + i, (height - y) - (i * 2)); //Left Inner Edge 

     } 
     g.setColor(oldColor); 
    } 

    public int getThickness() { 
     return thickness_; 
    } 

    public void setThickness(int i) { 
     thickness_ = i; 
    } 

    public boolean isBorderOpaque() { 
     return true; 
    } 

    public Insets getBorderInsets(Component c) { 
     return new Insets(thickness_, thickness_, thickness_, thickness_); 
    } 

}