使用JButton更改ImageBackground?

时间:2017-03-02 13:56:46

标签: java image swing user-interface awt

我希望能够使用简单的Jbutton更改背景。我将添加的背景和所有其他组件将在JPanel上移位。我已经弄清楚如何使用Java.awt设置背景,虽然我无法弄清楚如何重绘背景而不会出错。

public class StartPanel extends JPanel{ 
    private Image virus = "ImagePath";
    private Image ecoli = "ImagePath";  
    private Graphics g;
    private boolean img;

    public StartPanel(){        
        this.setLayout(null);       
        this.add(Button()); 
        img = true;


    }   

    private JButton Button(){
        JButton b = new JButton("a");
        b.setBounds(230,480,20,20);
        b.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                 img = !img;
                 repaint();
            }
        });
        return b;
    }   


    public void paint(Graphics g){
       If(img){
        g.drawImage(ecoli,0,0,this);
    } else {
       g.drawImage(virus,0,0,this);
   }
}
}

2 个答案:

答案 0 :(得分:0)

您不能只使用字符串初始化图像,而是需要以其他方式初始化它们。我相信最简单的方法是使用ImageIcon,如下所示:

Image ecoli = new ImageIcon("ImagePath").getImage();

答案 1 :(得分:-1)

如果你对你的awt-Image好了......

对于更改任务,只需使用你在actionlistener中切换的布尔女巫

public class StartPanel extends JPanel{

private BufferedImage virus;
private BufferedImage ecoli;

boolean pic1;


public StartPanel(){

    try{
       virus = ImageIO.read(new File("PathtoImage"));
       ecoli = ImageIO.read(new File("PathtoImage"));
    }
    catch (IOException ex){
        System.out.println("Error ;-)");
    }

    this.setLayout(null);
    this.add(Button());
    pic1 = true;

}

private JButton Button(){
    JButton b = new JButton("a");
    b.setBounds(230,480,20,20);
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
            pic1 = !pic1;
            repaint();
        }
    });
    return b;
}

protected void paintComponent(Graphics g){
    if(pic1)
        g.drawImage(ecoli,0,0,this);
    else
        g.drawImage(virus,0,0,this);
}

}

如果您有两个以上的图像,请将int与switch case结合使用