Why are graphics not appearing in JFrame?

倖福魔咒の 提交于 2020-01-05 04:33:10

问题


Below I included two of the classes in my Java program (Launcher and Controls). In the both classes, they create a JFrame, draw a background image, and add lines of text. I have looked at the code over and over, but for some reason the background image and the line of text are not appearing in the second class (Controls). Could anyone please explain to me why this is happening?

Launcher Class:

import hungerGames.Display;
import hungerGames.RunGame;
import hungerGames.input.InputHandler;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferStrategy;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;

public class Launcher extends JFrame implements Runnable {
public static final long serialVersionUID = 1L;

protected JPanel window = new JPanel();

private int width = 800;
private int height = 450;
boolean running = false;
Thread thread;

public Launcher(int id) {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        e.printStackTrace();
    }
    setUndecorated(true);
    setSize(new Dimension(width, height));
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setResizable(false);
    setVisible(true);
    window.setLayout(null);
    InputHandler input = new InputHandler();
    addKeyListener(input);
    addFocusListener(input);
    addMouseListener(input);
    addMouseMotionListener(input);
    startMenu();
}

public void updateFrame() {
    if (InputHandler.dragged) {
        Point p = getLocation();
        if (InputHandler.MouseDX != InputHandler.MousePX || InputHandler.MouseDX != InputHandler.MousePX) {
            setLocation(p.x + InputHandler.MouseDX - InputHandler.MousePX, p.y + InputHandler.MouseDY - InputHandler.MousePY);
        }
    }
}

public void startMenu() {
    running = true;
    thread = new Thread(this, "menu");
    thread.start();
}

public void stopMenu() {
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public void run() {
    while (running) {
        try {
            renderMenu();
        } catch (IllegalStateException e) {
            System.out.println("Handled");
        }
        updateFrame();
    }
}

private void renderMenu() throws IllegalStateException {
    BufferStrategy bs = this.getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(3);
        return;
    }
    Graphics g = bs.getDrawGraphics();
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, 800, 450);
    try {
        g.drawImage(ImageIO.read(Display.class.getResource("/main_menu.jpg")), 0, 0, 800, 450, null);
        if (InputHandler.mouseX >= 50 && InputHandler.mouseX <= 100 && InputHandler.mouseY >= 290 && InputHandler.mouseY <= 325) {
            g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 10, 295, 30, 33, null);
            if (InputHandler.MouseButton == 1) {
                dispose();
                new RunGame();
            }
        }
        if (InputHandler.mouseX >= 50 && InputHandler.mouseX <= 320 && InputHandler.mouseY >= 390 && InputHandler.mouseY <= 425) {
            g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 10, 395, 30, 33, null);
            if (InputHandler.MouseButton == 1) {
                dispose();
                new Controls();
            }
        }
        if (InputHandler.mouseX >= 400 && InputHandler.mouseX <= 490 && InputHandler.mouseY >= 290 && InputHandler.mouseY <= 325) {
            g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 360, 295, 30, 33, null);
            if (InputHandler.MouseButton == 1) {
                dispose();
                new Credits();
            }
        }
        if (InputHandler.mouseX >= 400 && InputHandler.mouseX <= 440 && InputHandler.mouseY >= 390 && InputHandler.mouseY <= 425) {
            g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 360, 395, 30, 33, null);
            if (InputHandler.MouseButton == 1) {
                System.exit(0);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    g.setColor(Color.WHITE);
    g.setFont(new Font("Agency FB", 0, 30));
    g.drawString("By Lawrence Zhao", 210, 275);
    g.setFont(new Font("Agency FB", 0, 40));
    g.drawString("Play", 50, 325);
    g.drawString("Controls and Options", 50, 425);
    g.drawString("Credits", 400, 325);
    g.drawString("Exit", 400, 425);
    g.dispose();
    bs.show();
}
}

Controls Class:

import hungerGames.Display;
import hungerGames.input.InputHandler;

import java.awt.Choice;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferStrategy;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;

public class Controls extends JFrame{
public static final long serialVersionUID = 1L;

protected JPanel window = new JPanel();

private int width = 720;
private int height = 450;
private Rectangle rResolution;
private Choice resolution = new Choice();

public Controls() {
    try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        e.printStackTrace();
    }
    setUndecorated(true);
    setSize(new Dimension(width, height));
    setLocationRelativeTo(null);
    setResizable(false);
    setVisible(true);
    window.setLayout(null);
    InputHandler input = new InputHandler();
    addKeyListener(input);
    addFocusListener(input);
    addMouseListener(input);
    addMouseMotionListener(input);

    renderControls();
    drawButtons();
    stopMenuThread();
}

private void stopMenuThread() {
    Display.getLauncherInstance().stopMenu();
}

private void drawButtons() {

    rResolution = new Rectangle(50,100, 100, 25);
    resolution.setBounds(rResolution);
    resolution.add("640, 400");
    resolution.add("800, 600");
    resolution.add("1024, 768");
    resolution.select(1);
    add(resolution);
}

private void renderControls() throws IllegalStateException {
    BufferStrategy bs = this.getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(3);
        return;
    }
    Graphics g = bs.getDrawGraphics();
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, 720, 450);
    try {
        g.drawImage(ImageIO.read(Display.class.getResource("/controls.jpg")),0, 0, 720, 450, null);
        if (InputHandler.mouseX >= 360 && InputHandler.mouseX <= 400 && InputHandler.mouseY >=270 && InputHandler.mouseY <=305) {
            g.drawImage(ImageIO.read(Controls.class.getResource("/pin.png")),360,270, 30, 33, null);
            if (InputHandler.MouseButton == 1) {
                Display.selection = resolution.getSelectedIndex();
                dispose();
                new Launcher(0);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    g.setColor(Color.WHITE);
    g.setFont(new Font("Agency FB", 0, 40));
    g.drawString("Exit", 400, 300);
    g.dispose();
    bs.show();
}

}


回答1:


It's clear that you don't understand how the buffering strategy is suppose to work.

I'd suggest you have a read through Double Buffering for some clues.

(ps, I don't have much experience with this side of the API either, but I got your code to work by simply reading through the above linked tut)

Update

Seems to work just fine for me...

Some notes.

  • Pre-load your images, otherwise you're wasting your time double buffering as the IO is going to slow you down.
  • Make sure your images exist and are begin loaded properly

.

public class BadPaint03 {

    public static void main(String[] args) {
        new BadPaint03();
    }

    public BadPaint03() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                Controls frame = new Controls();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }

    public class Controls extends JFrame {

        private int width = 720;
        private int height = 450;
        private Rectangle rResolution;
        protected JPanel window = new JPanel();
        private BufferedImage background;

        public Controls() {

            try {
                background = ImageIO.read(new File("/path/to/your/image"));
            } catch (Exception e) {
                e.printStackTrace();
            }

            setUndecorated(true);
            setSize(new Dimension(width, height));
            setLocationRelativeTo(null);
            setResizable(false);
            setVisible(true);
            window.setLayout(null);

            new Thread(new Runnable() {
                @Override
                public void run() {

                    while (true) {

                        renderControls();
                        try {
                            Thread.sleep(1000 / 24);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(BadPaint03.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }

                }
            }).start();

        }

        private void renderControls() throws IllegalStateException {
            BufferStrategy bs = this.getBufferStrategy();
            if (bs == null) {
                createBufferStrategy(3);
                return;
            }
            Graphics g = bs.getDrawGraphics();
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 720, 450);

            if (background != null) {

                int x = (720 - background.getWidth()) / 2;
                int y = (450 - background.getHeight()) / 2;
                g.drawImage(background, x, y, null);

            }

            g.setColor(Color.WHITE);
            g.setFont(new Font("Agency FB", 0, 40));
            g.drawString("Exit", 400, 300);
            g.dispose();
            bs.show();
        }
    }
}


来源:https://stackoverflow.com/questions/13557261/why-are-graphics-not-appearing-in-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!