2009-12-12 70 views
0

我已經創建了自定義按鈕。爲此,我重寫了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))); 
    } 



} 
+0

你爲什麼要這麼麻煩?爲什麼不使用IDE(NetBeans,Eclipse等)? – 2009-12-12 11:49:56

+1

Prasoon? IDE與自定義編寫的Swing控件有什麼關係? – Joey 2009-12-12 11:54:03

+0

@JOhannes:沒什麼,但是用IDE來設計GUI會更容易些,但是他需要知道基礎知識。 – 2009-12-12 11:57:10

回答

1

爲什麼你不只是調用super(g)上的paintComponent方法的第一行,並使用setText方法來改變按鈕上的字符串。

事情是這樣的:

protected void paintComponent(Graphics g) 
{ 
    super.paintComponent(g); 
    // do your customized painting here... 
} 
+0

超級(g)給我錯誤..「調用超級必須是構造函數的第一條語句」 – Nilesh 2009-12-12 12:00:52

+0

對不起,應該是super.paintComponent(g); – 2009-12-12 12:46:43

+0

這就是票 - 繪製背景反轉並首先進行自定義繪畫。 – Pool 2009-12-12 15:50:20

0

什麼是你想做,你從來沒有說過的實際需求?它看起來像你試圖在圖像上繪製文本。如果是這樣,那麼就沒有必要風俗畫,只需使用:

button.setHorizontalTextPosition(JButton.CENTER); 
button.setVerticalTextPosition(JButton.CENTER); 

您可以設置翻轉,並根據需要按下圖標。