2010-10-31 64 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