2010-10-31 75 views
1

我正在設計一個大城市中的公共交通優化系統。所以我有一個地圖上有一些點,但不關心它)
我所需要的是:我自己的JButton,它看起來像一個顏色填充的圓圈和附近的小文本標記。我在覆蓋paintComponent()方法時遇到了一些問題。圓形按鈕被正確繪製,但不是文本。
但是,當我手動調整窗口大小時,文本出現一秒鐘,然後重新繪製並消失。 希望你們理解我的需要,感謝您的幫助;)繪製自定義JButton和文本行

import java.awt.*; 
import javax.swing.*; 


public class JRoundButton extends JButton { 

String label; 
Color color; 
int x,y; 
public JRoundButton(Color color,int x,int y,String str) 
{ 
    label=str; 
    this.x=x; 
    this.y=y; 
    this.color=color;  
} 

protected void paintComponent(Graphics g) 
    { 
    super.paintComponent(g); 
    Dimension size = getPreferredSize(); 
    setPreferredSize(size); 
    this.setBounds(0, 0, 10, 10); 
    setContentAreaFilled(false); 

    g.setFont(new Font("Arial",Font.BOLD,14)); 
    g.drawChars(label.toCharArray(), 0, label.length(), 12,12); 
    g.fillOval(0,0,8,8); 
} 

public void paintBorder(Graphics g) 
    { 
    g.setColor(Color.white); 
    g.drawOval(0,0, 9, 9); 
} 
public static void main(String[] args) 
    { 
    JButton button = new JRoundButton(Color.GRAY,150,150,"Times Square"); 

    JFrame frame = new JFrame(); 
    frame.getContentPane().setBackground(Color.black); 
    frame.setSize(300, 300); 
    frame.setVisible(true); 
    frame.add(button); 
} 

}

回答

0

我只是欺騙和JButton的文本使用Unicode圈。例如: -

import javax.swing.*; 

JFrame frame = new JFrame(); 
frame.getContentPane().add(new JButton("<html><font size='+10' color='red'>&#x25CF;</font> I'm next to a red circle!</html>")); 
frame.pack(); 
frame.show(); 
1

似乎調用「的setBounds(0,0,10,10)」設置一個組件佔用空間太小,無法容納的文本字符串。將界限擴展到100px寬,並將點大小降至6看起來可以工作。

1

1)不要在paintComponent()方法中設置按鈕的屬性。

Dimension size = getPreferredSize(); 
setPreferredSize(size); 
this.setBounds(0, 0, 10, 10); 
setContentAreaFilled(false); 

擺脫上面的代碼。

2)不要在paintComponent()方法中設置圖形對象的字體。那是什麼setFont(...)方法用於。

3)沒有必要做任何自定義繪畫。如果你想要一個圓,然後添加一個圖標到JLabel。

4)不要重寫paintBorder()方法。如果你想要一個邊框,然後創建一個自定義邊框並使用setBorder()方法將其添加到按鈕。

總之,沒有必要延長按鈕。擺脫你的JRoundButton類。您的代碼應該簡單地看是這樣的:

JButton = new JButton("Times Square"); 
button.setFont(new Font("Arial",Font.BOLD,14)); 
button.setIcon(new OvalIcon(Color.WHITE, iconSize)); 

當然,你需要創建一個OvalIcon類的,但因爲只有三個方法,你已經知道這幅畫的代碼應該是什麼,很容易實現。

+0

非常感謝1),2)和4),但不是第三個,因爲我需要一個可點擊的圓圈和靠近....的文本行,所以這就是問題! – NavigatingYourSoul 2010-11-01 05:11:49

+0

那麼,你的方法也不能解決第三個要求。我不確定我是否理解這項要求。聽起來你需要面板上的兩個組件。帶有圖標的JButton和帶有文本的JLabel。或者你也許需要一個JCheckBox。 – camickr 2010-11-01 05:35:48