1

まず第一に、はい、私は初心者であることを知っています。これは、カスタムコンポーネントを作成する最初の試みです。

さて、私のプロジェクトでは、次の3つのことを行うカスタムボタンを作成しようとしています。

  1. 背景を描く
  2. 選択したアプリのアイコンを取得する
  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コンポーネントについてよく理解している人がいたら、良いチュートリアルや、あなたと同じようにそれを学ぶ方法を教えてください。

4

1 に答える 1

1

ええと、一つには、JButtonは画像を描くことができます。しかし、おそらく探しているのはJComponent.setPreferedSize()、次のドキュメントを確認することです。http: //docs.oracle.com/javase/6/docs/api/javax/swing/JComponent.html#setPreferredSize(java.awt.Dimension)

于 2012-05-22T21:55:08.167 に答える