我正在设计一个大城市中的公共交通优化系统。所以我有一个地图上有一些点,但不关心它)
我所需要的是:我自己的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