First of all, yes, I know I'm a newbie, and this is my first attempt at making a custom Component.
Okay, so in my project, I'm trying to make a custom button that does three things:
It can do all three of those, except that the button is tiny:
The icon is the Jar application and the name is "Test Application".
This is the paintComponent(Graphics) method in my class, AppButton:
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D antiAlias = (Graphics2D) g;
antiAlias.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.blue);
//g.fillRoundRect(x, y, width, height, arcWidth, arcHeight);
g.fillRoundRect(this.getX(), this.getY(), this.getWidth(), this.getHeight() - 25, 20, 20);
g.setColor(Color.red);
FontMetrics metrics = g.getFontMetrics();
int widthOfAppName = metrics.stringWidth(this.appName);
g.drawString(this.appName, this.getWidth() / 2 - (widthOfAppName / 2), this.getHeight() - 10);
File refrenceFile = new File(this.appURL);
try {
if (refrenceFile.exists()) {
ShellFolder sf = ShellFolder.getShellFolder(refrenceFile);
this.appIcon = new ImageIcon(sf.getIcon(true));
g.drawImage(this.appIcon.getImage(), this.getWidth() / 2 - (this.appIcon.getIconWidth() / 2),
this.getHeight() / 2 - (this.appIcon.getIconHeight() / 2), JLaunch.theFrame);
//Draw the centered Image
} else {
ImageIcon noImageFound = getNoImageAvailable();
//g.drawImage(img, x, y, observer)
g.drawImage(noImageFound.getImage(), this.getWidth() / 2 - (noImageFound.getIconWidth() / 2),
this.getHeight() / 2 - (noImageFound.getIconHeight() / 2), JLaunch.theFrame);
//Draw the centered Image
}
} catch (Exception e) {
e.printStackTrace();
}
}
On a side note, if anyone has a good understanding about custom Swing Components, can you also please point me to a good tutorial or a way of learning it like you did?
Well, for one, JButton can draw images. But what you are probably looking for is JComponent.setPreferedSize()
You can check out the documentation here: http://docs.oracle.com/javase/6/docs/api/javax/swing/JComponent.html#setPreferredSize(java.awt.Dimension).