从其他类实例化时,JPanel不会打开

时间:2014-05-08 02:19:00

标签: java jframe jpanel

在我的主类中,我调用一个类,在实例化时,应该显示它的JFrame窗口。但事实并非如此。当我通过Eclipse运行项目之前,我曾经有过这个课程。现在,通过命令行运行它,它不起作用:(。

从我的主要方法:

PaintTitleMovie q = new PaintTitleMovie();

Jframe类:

public class PaintTitleMovie extends JPanel implements MouseListener {

    Image image;
    Font ConfettiFinal = new Font("Analog", 1, 20); // fail safe
    static JFrame frame = new JFrame();

    public PaintTitleMovie() {
        image = Toolkit.getDefaultToolkit().createImage("src/Title2.gif");
        try {
            Font Confetti = Font.createFont(Font.TRUETYPE_FONT, new File(
                    "src/Fonts/Confetti.ttf"));
            ConfettiFinal = Confetti.deriveFont(1, 50);
        } catch (FontFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        addMouseListener(this);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null) {
            g.drawImage(image, 0, 0, this);
        }
        // draw exit button
        g.setColor(Color.BLUE);
        g.fillRect(990, 50, 210, 100);
        g.setColor(Color.BLACK);
        g.fillRect(1000, 60, 190, 80);
        g.setColor(Color.WHITE);
        g.setFont(ConfettiFinal);
        g.drawString("Continue", 1000, 120);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {

                frame.add(new PaintTitleMovie());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(1200, 800);
                frame.setUndecorated(true);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
                SongTitle s = new SongTitle();
            }
        });
    }

    @Override
    public void mouseReleased(MouseEvent arg0) {
        // TODO Auto-generated method stub
        int x = arg0.getX();
        int y = arg0.getY();

        if (x >= 990 && y >= 50 && y <= 150) {
            this.setVisible(false);
            frame.dispose();
            PaintMenu load = new PaintMenu(); // load paint menu
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这个src/Title2.gif会出现问题,构建程序时src目录将不存在。

Toolkit.getDefaultToolkit().createImage(String)还假定资源是文件系统上的文件,但应用程序上下文(或jar文件)中包含的任何内容都被视为嵌入式资源,不能视为文件。

相反,您可能需要使用更像

的内容
image = ImageIO.read(getClass().getResource("/Title2.gif"));

这将返回BufferedImage,但如果无法加载图像,也会抛出IOException。如果gif是动画gif,你需要使用更像

的东西
image = new ImageIcon(getClass().getResource("/Title2.gif"));

您的字体也是如此,但在这种情况下,您可能需要使用

Font Confetti = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream(
                "/Fonts/Confetti.ttf"));

如果您正在使用Eclipse,则可能需要将这些资源移出src目录以及与src目录相同级别的“resources”目录,以便它们能够被包括在最终版本中。

相关问题