繁体   English   中英

动态更改JPanel的背景图像

[英]Dynamically change Background Image of a JPanel

尝试ti改变jpanel的BG图像,但我不能在任何常规方法上调用poaint,它在我构建构造函数但我不想重建构造函数时工作得很好。

....

通过在我的中心框架中放置标签并调用setIcon来找到解决方案,但我需要能够提取相关信息,因此我需要找到一种方法将值存储到我的Jtoggle按钮(Race或类的ID)所以我可以获取它的图片并更改图标)

想法? 一切都在iff语句之外编译,这是我的观点

RaceButtons_lft[i] =  new JToggleButton();
RaceButtons_lft[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JToggleButton cb = (JToggleButton)ae.getSource();
for (int j=0; j<MyRaceArray.size(); j++)
{
if (MyRaceArray.get(j).getraceID() == combo_contents.getIndex()){//here is my sticking point, i need to find a way to match MyRaceArray's getRaceID to some value saved withthe Toggle button
final ImageIcon BGCSMs = ScaledImageIcon("Fantasy_Landscape_01.jpg", "Profile Pic", (468-(60*2)), 285);
picLabel.setIcon(BGCSMs);
}//if
}//for
}//action performed;
});//button add action listener

调用

super.paintComponent(..)

可能 - 取决于超类 - 用背景颜色填充组件。

public void paintComponent(Graphics g) {
  // Let UI Delegate paint first, which 
  // includes background filling since 
  // this component is opaque.

  super.paintComponent(g);       
  g.drawString("This is my custom Panel!",10,20);
  redSquare.paintSquare(g);
}

(参见对油漆机制的仔细研究 )。 在这种情况下,您不需要重绘(..)。

您可能会遇到许多问题,我们无法看到这些问题,因为我们没有足够的背景......

  • 你可能有一个引用问题,而不是试图repaint屏幕上的组件,你无意中得到了错误的引用...
  • 你可能会影响你的变量......
  • 你可以画到不透明的组件......

假设您发布的代码是线性的(即,它以正确的顺序出现在您的代码中或者足够接近它),我可以看到一个可能的问题......

ImageIcon RCicon = createImageIcon(temp_race.getActiveHeadshot(), temp_race.getRaceNameString(race.getraceID()));
Image RCimg = RCicon.getImage();
RCimg = RCimg.getScaledInstance((468-(60*2)), 285, java.awt.Image.SCALE_SMOOTH);

portraitCenterOptions.setBackground(Color.White){
    protected void paintComponent(Graphics h)
    {
        //...//
        // There is no way that this reference can be valid...
        // The image created above will only have a local reference unto itself
        // suggestion that you're shadowing your variables...
        final ImageIcon bodypicSM = new ImageIcon(RCimg);
        //...//
    }
};

但没有一个实际的例子,就不可能知道......

在此输入图像描述

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.text.DateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ChangeBackground {

    public static void main(String[] args) {
        new ChangeBackground();
    }

    public ChangeBackground() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final PaintPane pane = new PaintPane();
                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(pane);

                JButton change = new JButton("Change");
                change.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        pane.changeBackground();
                        pane.repaint();
                    }
                });

                frame.add(change, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class PaintPane extends JPanel {

        private BufferedImage bg;
        private int changes = 0;

        public PaintPane() {
            changeBackground();
        }

        public void changeBackground() {

            bg = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = bg.createGraphics();
            FontMetrics fm = g.getFontMetrics();
            g.setColor(getForeground());
            String[] text = {
                "I've been changed " + changes + " times", 
                "Last changed at " + DateFormat.getDateTimeInstance().format(new Date())};
            int y = (200 - (fm.getHeight() * 2)) / 2;
            for (String value : text) {
                int x = (200 - fm.stringWidth(value)) / 2;
                g.drawString(value, x, y + fm.getAscent());
                y += fm.getHeight();
            }
            g.dispose();
            changes++;

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g); 
            int x = (getWidth() - bg.getWidth()) / 2;
            int y = (getHeight() - bg.getHeight()) / 2;
            g.drawImage(bg, x, y, this);
        }

    }

}

完成对背景的更改后,在组件上调用repaint()

所以最终尝试了一些东西,只是懒得,在中心添加了一个标签并称为“SetIcon,做我需要它做的事情,感谢你的想法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM