简体   繁体   中英

I created code for controlling a image in swing, but I can't see anything, why?

I run this code and what I see is just big blank frame, why can't I see the image of car on it, I created a panel that contains a label that holds a image of car, I created a keylkisteners for backward and foreward, I run it and see nothing, just the blunk frame?

    public class carGame implements KeyListener {
    JFrame frame;
    JPanel panel;
    JLabel carPane;

    public carGame(){
        frame=new JFrame();
        frame.setBounds(300, 400, 1200, 600);
        panel=new JPanel();
        panel.setBounds(300, 400, 1200, 100);
        ImageIcon car=new ImageIcon("rsz_1car-blogspot-blue.png");
        carPane=new JLabel();
        carPane.setBounds(400, 400, 100, 100);
        carPane.setIcon(car);
        panel.add(carPane);
        frame.add(panel);
        frame.show(true);
        frame.setVisible(true);     
    }


    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
        if(e.getKeyCode()==KeyEvent.VK_RIGHT)
            this.carPane.setBounds(carPane.getX()+30, carPane.getY(), carPane.getWidth(), carPane.getHeight());
        if(e.getKeyCode()==KeyEvent.VK_LEFT)
            this.carPane.setBounds(carPane.getX()-30, carPane.getY(), carPane.getWidth(), carPane.getHeight());
    }



public class testing {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //windowMa frame=new windowMa();
        carGame game=new carGame();
    }
}

Try the .setVisible() method ! Also, the swing it needs to paint itself . but first try the setVisible method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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