我正在設計一個大城市中的公共交通優化系統。所以我有一個地圖上有一些點,但不關心它)
我所需要的是:我自己的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);
}
}
非常感謝1),2)和4),但不是第三個,因爲我需要一個可點擊的圓圈和靠近....的文本行,所以這就是問題! – NavigatingYourSoul 2010-11-01 05:11:49
那麼,你的方法也不能解決第三個要求。我不確定我是否理解這項要求。聽起來你需要面板上的兩個組件。帶有圖標的JButton和帶有文本的JLabel。或者你也許需要一個JCheckBox。 – camickr 2010-11-01 05:35:48