2014-05-16 22 views
1

對於我的項目,我需要創建可自定義的按鈕。除了我有問題,我不知道如何解決它。 我有一個我的按鈕的背景圖片,我希望它是可擴展的X和Y根據文本將在沒有損失的質量。 你有什麼想法嗎?Java中的設計按鈕(如CSS)

background image example

+2

你應該注意一下的Java FX CSS文檔http://docs.oracle。 com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html – diegoaguilar

回答

5

擺有一個可插拔的外觀&感覺它允許改變其部件的由ComponentUI的方式出現(在這種情況下:一個ButtonUI)。

您的按鈕

例子:

enter image description here

class StyledButtonUI extends BasicButtonUI { 

    @Override 
    public void installUI (JComponent c) { 
     super.installUI(c); 
     AbstractButton button = (AbstractButton) c; 
     button.setOpaque(false); 
     button.setBorder(new EmptyBorder(5, 15, 5, 15)); 
    } 

    @Override 
    public void paint (Graphics g, JComponent c) { 
     AbstractButton b = (AbstractButton) c; 
     paintBackground(g, b, b.getModel().isPressed() ? 2 : 0); 
     super.paint(g, c); 
    } 

    private void paintBackground (Graphics g, JComponent c, int yOffset) { 
     Dimension size = c.getSize(); 
     Graphics2D g2 = (Graphics2D) g; 
     g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
     g.setColor(c.getBackground().darker()); 
     g.fillRoundRect(0, yOffset, size.width, size.height - yOffset, 10, 10); 
     g.setColor(c.getBackground()); 
     g.fillRoundRect(0, yOffset, size.width, size.height + yOffset - 5, 10, 10); 
    } 
} 

測試主要方法:

public static void main (String[] args) { 
    JFrame f = new JFrame("Button UI Test"); 
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
    JPanel p = new JPanel(); 
    p.setBackground(Color.white); 
    f.setContentPane(p); 
    p.setLayout(new FlowLayout(5, 5)); 
    p.setBorder(new EmptyBorder(10, 10, 10, 10)); 

    for (int i = 1; i <= 5; i++) { 
     final JButton button = new JButton("Button #" + i); 
     button.setFont(new Font("Calibri", Font.PLAIN, 14)); 
     button.setBackground(new Color(0x2dce98)); 
     button.setForeground(Color.white); 
     // customize the button with your own look 
     button.setUI(new StyledButtonUI()); 
     p.add(button); 
    } 

    f.pack(); 
    f.setLocation(500, 500); 
    f.setVisible(true); 
} 
+1

非常感謝,我不知道這是可能的。你以最簡單的方式解決了我的問題。再一次,謝謝:) 通過利弊,我怎麼能做更詳細的同樣的事情這樣的[設計](http://speckycdn.sdm.netdna-cdn.com/wp-content/uploads/2012/ 01/preview640.jpg)? – TheNawaKer

1

您可以縮放圖像,並創建一個ImageIcon。事情是這樣的:

ImageIcon icon = new ImageIcon("img.png"); 
Image scaledImg = icon.getImage().getScaledInstance(newWidth, newHeight, java.awt.Image.SCALE_SMOOTH); 
icon = new ImageIcon(scaledImg); 
JButton button = new JButton(icon); 
button.setHorizontalTextPosition(JButton.CENTER); 
button.setVerticalTextPosition(JButton.CENTER);