Fórum [RESOLVIDO] Colocar imagem de fundo em um JButton #569625
09/11/2011
0
William Seefeld
Curtir tópico
+ 0Posts
09/11/2011
Douglas Eric
public class BackgroundButton extends javax.swing.JButton{
//Carrega a sua imagem
ImageIcon imagem = new ImageIcon(this.getClass().getResource("images/Fundo.png"));
public void paintComponent(Graphics g) {
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
final Image backgroundImage = imagem.getImage();
double scaleX = getWidth() / (double) backgroundImage.getWidth(null);
double scaleY = getHeight() / (double) backgroundImage.getHeight(null);
AffineTransform xform = AffineTransform.getScaleInstance(scaleX, scaleY);
((Graphics2D) g).drawImage(backgroundImage, xform, this);
String texto = this.getText();
// Find the size of string s in font f in the current Graphics context g.
Font font = new Font("Dialog", Font.PLAIN, 11);
java.awt.FontMetrics fm = g.getFontMetrics(font);
java.awt.geom.Rectangle2D rect = fm.getStringBounds(texto, g);
int textWidth = (int)(rect.getWidth());
int textHeight = (int)(rect.getHeight());
Dimension size = this.getSize();
int x = (size.width - textWidth)/2;
int y = (size.height - textHeight)/2 + fm.getAscent();
g.drawString(texto, x, y);
}
}
Gostei + 0
10/11/2011
Douglas Eric
Gostei + 0
10/11/2011
Douglas Eric
Gostei + 0
10/11/2011
Douglas Eric
public class BackgroundHtmlButton extends javax.swing.JButton{
JLabel label ;
ImageIcon imagem = new ImageIcon(this.getClass().getResource("images/Fundo.png"));
public BackgroundHtmlButton(String text){
this(); //ops, tinha faltado essa linha!
label.setText(text);
}
public BackgroundHtmlButton(){
label = new JLabel();
this.add(label);
}
public void paintComponent(Graphics g) {
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
final Image backgroundImage = imagem.getImage();
double scaleX = getWidth() / (double) backgroundImage.getWidth(null);
double scaleY = getHeight() / (double) backgroundImage.getHeight(null);
AffineTransform xform = AffineTransform.getScaleInstance(scaleX, scaleY);
((Graphics2D) g).drawImage(backgroundImage, xform, this);
}
/**
* Para redirecionar o setText para o label
*
* @param text, texto do botão em html
*/
@Override
public void setText(String text){
label.setText(text);
}
}
Gostei + 0
11/11/2011
Douglas Eric
Gostei + 0
11/11/2011
Douglas Eric
Gostei + 0
11/11/2011
Douglas Eric
public BackgroundHtmlButton(String text){
label = new JLabel();
this.add(label);
label.setText(text);
}
public BackgroundHtmlButton(){
label = new JLabel();
this.add(label);
}
Gostei + 0
11/11/2011
Douglas Eric
Gostei + 0
11/11/2011
Douglas Eric
Gostei + 0