まず第一に、はい、私は初心者であることを知っています。これは、カスタムコンポーネントを作成する最初の試みです。
さて、私のプロジェクトでは、次の3つのことを行うカスタムボタンを作成しようとしています。
- 背景を描く
- 選択したアプリのアイコンを取得する
- ボタンにアプリの名前を描きます。
ボタンが小さいことを除いて、これら3つすべてを実行できます。
アイコンはJarアプリケーションで、名前は「TestApplication」です。
これは、私のクラスAppButtonのpaintComponent(Graphics)メソッドです。
@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();
}
}
ちなみに、カスタムSwingコンポーネントについてよく理解している人がいたら、良いチュートリアルや、あなたと同じようにそれを学ぶ方法を教えてください。