通过点击按钮-更换JPanel的背景图片

首先准备两张图片:

D:\pachong\1.jpg

D:\pachong\2.jpg

 

下面是源码:

Test.java

 

public class Test {
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());

        MyJPanel myJPanel = new MyJPanel();

        JPanel jPanel = new JPanel();
        JButton jButton = new JButton("上");
        JButton jButton1 = new JButton("下");
        jPanel.add(jButton);
        jPanel.add(jButton1);

        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MyJPanel.deleteI();
                myJPanel.repaint();
            }
        });

        jButton1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MyJPanel.addI();
                myJPanel.repaint();
            }
        });



        frame.add(myJPanel,BorderLayout.CENTER);
        frame.add(jPanel,BorderLayout.SOUTH);

        frame.setSize(Util.WIDTH,Util.HEIGTH);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}


MyJpanel.java

 

 

public class MyJPanel extends JPanel {
    public static  int i = 1;

    public static void addI()
    {
        i++;
    }

    public static void deleteI()
    {
        i--;
    }

    public void paint(Graphics g)
    {
        int x =0;
        int y = 0;
        String swl = "D:\\pachong\\" + i + ".jpg";
        System.out.println(swl);
        ImageIcon imageIcon  = new ImageIcon(swl);
        g.drawImage(imageIcon.getImage(),x,y,getSize().width,getSize().height,this);
    }
//    public void paintComponent(Graphics g)
//    {
//        super.paintComponent(g);
//        int x = 0;
//        int y = 0;
//        String swl = "D:\\pachong\\" + 1 + ".jpg";
//        System.out.println(swl);
//        ImageIcon imageIcon  = new ImageIcon(swl);
//        g.drawImage(imageIcon.getImage(),x,y,getSize().width,getSize().height,this);
//        i++;
//    }
}

 

 

 

 

 

 

你可能感兴趣的:(other)