在图像上添加组件

时间:2015-06-28 07:09:18

标签: java swing components

我一直在互联网上寻找如何在图像上添加组件的解决方案。我试过这个:

    setContentPane(new JComponent(){
        @Override
        protected void paintComponent(Graphics g){
            URL url = ...;
            if(url==null){
                //... Irelevant
                return;
            }
            try {
                BufferedImage img = ImageIO.read(url);
                g.drawImage(img,0 ,0, this);
                super.paintComponents(g);
            } catch (IOException e) {
                //... Irelevant
                e.printStackTrace();
                return;
            }

        }
    });
    nameLabel=new JLabel("<html><body>"+Main.translateColorsToHTML(name)+"</body></html>");
    nameLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
    nameLabel.setVisible(true);
    add(nameLabel);

哪个不起作用,所以我试过这个:

    URL url = ...;//Fetching the url
    if(url==null){
        //... Unrelevant
        return;
    }
    try {
        BufferedImage img = ImageIO.read(url);
        invImg = new JLabel(new ImageIcon(img));
        invImg.setMaximumSize(new Dimension(340, 250));
        setContentPane(invImg);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

然后将一个组件添加到内容窗格/框架本身。 我绝对不知道如何做到这一点,任何帮助将不胜感激。 提前谢谢!

2 个答案:

答案 0 :(得分:1)

我找到了一个可行的解决方案:

BufferedImage img = ImageIO.read(url);
invImg = new JLabel();
invImg.setIcon(new ImageIcon(img));
invImg.setLayout(new BoxLayout(invImg, BoxLayout.Y_AXIS));
setContentPane(invImg);

答案 1 :(得分:0)

嘿嘿要在 Person *person = [[Person alloc] init]; person.name = @"Alex"; // Age is a class with properties value (i.e. 100) and unit (i.e. year) Age *age = [[Age alloc] init]; age.value = @100; person.age = age; NSMutableArray *people = [[NSMutableArray alloc] init]; [people addObject:person]; for (id person in people) { person.age.value } 上添加jPanel? (这几乎总是一个更好的主意)

JFrame上添加jPanel,并在其上绘图。

JFrame Override paint(Graphics2D g) jPanel方法(继承自JComponent)并绘制您的图像

yourPanel = new javax.swing.JPanel(){
            @Override
            public void paint(Graphics g) {
                super.paint(g);
                g.drawImage(yourImage, null, x, y);
            }
}