动态更改JPanel的背景图像

时间:2013-06-07 07:42:26

标签: java swing jpanel paintcomponent

尝试改变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

4 个答案:

答案 0 :(得分:1)

调用

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

(见A Closer Look at the Paint Mechanism)。在这种情况下,您不需要重绘(..)。

答案 1 :(得分:1)

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

  • 您可能会遇到参考问题,而不是尝试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);
        //...//
    }
};

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

enter image description here

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

    }

}

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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