Java 动态更改JPanel的背景图像

Java 动态更改JPanel的背景图像,java,swing,jpanel,paintcomponent,Java,Swing,Jpanel,Paintcomponent,尝试更改jpanel的BG映像,但我不能在任何普通方法上调用poaint,它在我构建构造函数时非常有效,但我不想重建构造函数 通过在我的中间框架中放置标签并调用setIcon,我找到了一种解决方案,但我需要能够提取相关信息,因此我需要找到一种方法将值存储到我的Jtoggle按钮(比赛或职业的id,以便我可以获取它的图片并更改图标) 想法?一切都在iff语句之外编译,这是我的症结所在 RaceButtons_lft[i] = new JToggleButton(); RaceButtons_l

尝试更改jpanel的BG映像,但我不能在任何普通方法上调用poaint,它在我构建构造函数时非常有效,但我不想重建构造函数

通过在我的中间框架中放置标签并调用setIcon,我找到了一种解决方案,但我需要能够提取相关信息,因此我需要找到一种方法将值存储到我的Jtoggle按钮(比赛或职业的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
RaceButtons_lft[i]=新的JToggleButton();
RaceButtons_lft[i].addActionListener(新ActionListener(){
已执行的公共无效行动(行动事件ae){
JToggleButton cb=(JToggleButton)ae.getSource();
对于(int j=0;j在完成对后台的更改后调用组件上的

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);
}

(请参阅)。在这种情况下,您不需要重新绘制(..)。

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

  • 您可能存在引用问题,而不是尝试在屏幕上重新绘制组件,而是无意中获得了错误的引用
  • 你可能在隐藏你的变量
  • 你可以画一个不透明的组件
假设您发布的代码是线性的(即,它在您的代码中以这种精确的顺序出现或与之足够接近),我可以看到一个可能的问题

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);
        }

    }

}


因此,最终尝试了一些事情,只是变得懒惰,在中心添加了一个标签,并称为"SetIcon,做了我需要它做的事情,谢谢你的想法。

你在更改图像后尝试调用
repaint
了吗…?你也应该传递
this
,因为
drawImage
方法的
ImageObserver
参数修改了OP,希望我现在能更好地解释这个问题
是什么>肖像中心选项
?它是从什么扩展而来的?这是一个非常简单的jane Jpanel我将编辑OP,了解如何设置链接并找到各种解决方案,仍然无法找到匹配数据的方法来找到正确的图片,但可能有人有想法如果OP更改了图像,他们需要调用
重新绘制
,以便o更新它…你是对的-没有看到他在操纵图像。但是阅读教程会有所帮助:-)你建议先放置
super。paintComponent
仍然有效,甚至可能被证明是正确的;)