自定义按钮大小不正确?

时间:2012-05-22 21:39:14

标签: java jcomponent

首先,是的,我知道我是新手,这是我第一次尝试制作自定义组件。

好的,所以在我的项目中,我正在尝试制作一个自定义按钮,它可以完成三件事:

  1. 绘制背景
  2. 获取所选应用的图标
  3. 在按钮中绘制应用程序的名称。
  4. 它可以完成所有这三个,除了按钮是 tiny

    pic

    图标是Jar应用程序,名称是“Test Application”。

    这是我的类中的paintComponent(Graphics)方法,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();
        }
    }
    

    另外,如果有人对自定义Swing组件有很好的理解,你还可以指点一个好的教程或者像你一样学习它吗?

1 个答案:

答案 0 :(得分:1)

嗯,一方面,JButton可以绘制图像。但您可能正在寻找的是JComponent.setPreferedSize()您可以在此处查看文档:{​​{3}}。

相关问题