我已經創建了自定義按鈕。爲此,我重寫了paintComponenet方法。如何在這樣的按鈕上設置按鈕文字?我試着用drawString方法做它。但是,我應該給哪些x,y值? (g.drawString(「button text」,x,y))。如果有人已經處理過,請直到我。Java Swing JButton
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
DefaultButtonModel bmodel = (DefaultButtonModel) super.getModel();
Image im = (new ImageIcon("image")).getImage();
System.out.println("im is "+im.getSource());
System.out.println("widthis" + im.getWidth(this));
int imageX = (getWidth() - im.getWidth(this)) /2;
int imageY = (getHeight() - im.getHeight(this))/2;
if(!super.isEnabled()) {
System.out.println("in disabled");
g.drawImage(disabled, imageX, imageY, this);
g.drawString(super.getText(), super.getX(),(int) (super.getY()/(1.9)));
}
else {
if(bmodel.isPressed()) {
System.out.println("in pressed");
g.drawImage(down, imageX, imageY, this);
} else if(bmodel.isRollover()) {
System.out.println("in roll overed");
g.drawImage(highlight, imageX, imageY, this);
} else if(bmodel.isEnabled()) {
System.out.println("in enabled");
g.drawImage(normal, imageX, imageY, this);
} else {
System.out.println("in else");
g.drawImage(normal, imageX, imageY, this);
}
g.drawString(super.getText(), super.getX(),(int) (super.getY()/(2.5)));
}
}
你爲什麼要這麼麻煩?爲什麼不使用IDE(NetBeans,Eclipse等)? – 2009-12-12 11:49:56
Prasoon? IDE與自定義編寫的Swing控件有什麼關係? – Joey 2009-12-12 11:54:03
@JOhannes:沒什麼,但是用IDE來設計GUI會更容易些,但是他需要知道基礎知識。 – 2009-12-12 11:57:10