簡體   English   中英

未顯示要移動到 JFrame 的圖像

[英]The Image to be moved to JFrame is not displayed

我試圖制作一個常規程序來顯示移動圖像,我不確定我做錯了什么,當代碼啟動時,我只得到一個空程序。 也許它實際上在移動,但我沒有把它放在可見的地方,我不確定,我會在這里發布代碼。

我在 NetBeans 工作也許這有點問題,因為那里的一切都必須預先確定並且只是真實的類,而不是我。

主要的:

public class Main {
    public static void main(String[] args) {
        new MyFrame();
    }
}

J幀:

public class MyFrame extends JFrame {
    MyPanel panel;

    public MyFrame() {
        initComponents();

        panel = new MyPanel();

        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.add(panel);
        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MyFrame().setVisible(true);
            }
        });
    }
}

J面板:

public class MyPanel extends JPanel implements ActionListener {
    final int PANEL_WIDTH = 500;
    final int PANEL_HEIGHT = 500;
    Image enemyRed, enemyBlue, enemyYellow, enemyPink, packMan;
    Timer timer;
    int xBrzina = 1;
    int yBrzina = 1;
    int x = 0;
    int y = 0;

    public MyPanel() {
        initComponents();
        this.setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));

        enemyRed = new ImageIcon("C:\\Users\\SMRTNIK\\Documents\\enemy.png").getImage();
        timer = new Timer(100, null);
    }

    public void paint(Graphics g) {
        Graphics2D G2D = (Graphics2D) g;
        G2D.drawImage(enemyRed, x, y, null);

        super.paint(g);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (x >= PANEL_WIDTH - enemyRed.getWidth(null) || x < 0) {
            xBrzina = xBrzina * -1;
        }
        x = x + xBrzina;
        if (y >= PANEL_WIDTH - enemyRed.getWidth(null) || y < 0) {
            yBrzina = yBrzina * -1;
        }
        repaint();
    }
}

也許創建新的普通類並插入該代碼,但不要插入那些預定義的元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM