为什么图形不显示在JFrame中? [英] Why are graphics not appearing in JFrame?

查看:111
本文介绍了为什么图形不显示在JFrame中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我包含了我的Java程序中的两个类(Launcher和Controls)。在这两个类中,他们创建一个JFrame,绘制背景图像,并添加文本行。我一遍又一遍地查看了代码,但由于某些原因,背景图像和文本行并未出现在第二类(控件)中。任何人都可以向我解释为什么会发生这种情况?



启动器类:

  import hungerGames.Display; 
导入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;

保护JPanel窗口= new JPanel();

private int width = 800;
private int height = 450;
布尔运行= false;
线程线程;

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(px + InputHandler.MouseDX - InputHandler.MousePX,py + 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;
}
图形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); (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();
新的RunGame(); $(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();
新的Controls(); (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();
新增学分(); $(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();


$ / code $ / pre

控制类:

  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;

保护JPanel窗口= new JPanel();

private int width = 720;
private int height = 450;
私人矩形rResolution;
私人选择分辨率=新选择();

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(分辨率);


private void renderControls()throws IllegalStateException {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
图形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); (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();
新启动器(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();
}

}

解决方案

很显然,你不明白缓冲策略是如何工作的。



我建议你阅读通过双缓冲获得一些线索。



(ps,我对API的这一面也没有太多经验,但是我通过简单阅读上面链接的tut就可以使你的代码工作)。



更新



似乎对我来说工作得很好...




一些笔记。




  • 预加载您的图片,否则您会浪费时间双倍缓冲,因为IO会让您减慢速度。

  • 确保您的图片存在并开始正确加载



  public class BadPaint03 {

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

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

控制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;
私人矩形rResolution;
protected JPanel window = new JPanel();
私有BufferedImage背景;

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);
$ b $ 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);
}

}

}
})。


$ b private void renderControls()throws IllegalStateException {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
图形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();
}
}
}


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();
}

}

解决方案

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();
        }
    }
}

这篇关于为什么图形不显示在JFrame中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆