草庐IT

java - 我的 JFrame 没有显示任何内容

coder 2024-03-31 原文

我正在尝试为我的游戏引擎架构类(class)构建一个简单的游戏基础。但是我的 JFrame 不会显示任何内容。

我的代码目前结构如下:

Implementation.java(这是我正在创建的引擎包的任意实现)

public class Implementation {
    public static void main(String[] args){
        World w = new World("Hej", "M:\\workspace\\SP6\\pics\\tulips.jpg",1024,768);
    }
}

世界.java

public class World extends JFrame{
private static final long serialVersionUID = 1L;
private SpritePanel spritePanel;
private JPanel bottom;
private int width;
private int height;

public World(String windowCaption, String bgPath, int width, int height){
    super(windowCaption);

    spritePanel = new SpritePanel(bgPath);
    add(spritePanel, BorderLayout.CENTER);
    System.out.println(spritePanel);

    bottom = new JPanel();
    bottom.add(new JLabel("Hej"));
    add(bottom, BorderLayout.SOUTH);

    Dimension size = new Dimension(width,height);
    setSize(size);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    pack();
    setVisible(true);

    validate();
    repaint();      
}

Sprite 面板.java

public class SpritePanel extends JPanel {
private static final long serialVersionUID = 1L;
private ImageIcon background;
private ArrayList<Sprite> sprites = new ArrayList<Sprite>();

public SpritePanel(String bgPath){
    background = new ImageIcon(bgPath);
    setLayout(null);
    Dimension size = new Dimension(background.getIconWidth(), background.getIconHeight());
    setPreferredSize(size);
    setMaximumSize(size);
    setMinimumSize(size);
}

@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(background.getImage(), 0, 0, this);
    System.out.println("painted panel");
}
}

所以目前的基本操作流程(据我所知):

  1. 我在实现中创建了一个新的 World 对象
  2. 使用给定的参数调用 World-constructor
  3. 设置窗口标题(有效)
  4. 我使用给定的 bgPath 创建一个新的 SpritePanel 对象
  5. 调用 SpritePanel 构造函数并将 ImageIcon 设置为给定路径中存在的图像
  6. SpritePanel 添加到 BorderLayout.CENTER 中的框架
  7. 我将新的 JPanel 添加到 BorderLayout.CENTER 中的框架
  8. 我设置尺寸和东西
  9. 我打包并将框架设置为可见
  10. 我验证并重新绘制

问题是 JPanel 和 SpritePanel 中的 paintComponent 方法似乎没有被调用。如您所见,我在 SpritePanel 的 paintComponent 中添加了一个 System.out.println,并且该行从未执行过。

我注意到的另一件事是,狼群似乎知道组件在那里。因为如果我评论这三行

spritePanel = new SpritePanel(bgPath);
add(spritePanel, BorderLayout.CENTER);
System.out.println(spritePanel);

当我运行程序时,窗口大小缩小到“底部”-JPanel 的大小。我看不到我添加到面板的 JLabel,但窗口大小就是它的大小。所以 pack() 方法似乎是在寻找我的组件的尺寸。

如果我评论添加底部面板的三行,窗口大小将减小到没有高度和它从标准图标获得的宽度。

我一直在尝试不同的方法来让它工作,但无济于事。我以前用 Swing 编程过并制作了工作程序,但我似乎无法在这里找到问题。

非常感谢帮助。

最佳答案

您的字符串路径可能有问题。但是你应该做的是,你应该读取一个 URL,而不是读取一个文件,从类路径加载。在部署时,您会发现文件路径不起作用,因此最好将您的图像打包为 embedded resource。 ,将图像放在类路径中。这样做时我没有遇到任何问题。这就是我所做的。

  • 将路径更改为相对于我的类路径的路径

    World w = new World("Hej", "/resources/stackoverflow5.png", 1024, 768);
    
  • 从文件加载更改为从我的类路径中的 URL 加载

    background = new ImageIcon(SpritePanel.class.getResource(bgPath));
    
  • 将图片放在我类路径的resources包中

一切正常

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Implementation {

    public static void main(String[] args) {
        World w = new World("Hej", "/resources/stackoverflow5.png", 1024, 768);
    }
}

class World extends JFrame {

    private static final long serialVersionUID = 1L;
    private SpritePanel spritePanel;
    private JPanel bottom;
    private int width;
    private int height;

    public World(String windowCaption, String bgPath, int width, int height) {
        super(windowCaption);

        spritePanel = new SpritePanel(bgPath);
        add(spritePanel, BorderLayout.CENTER);
        System.out.println(spritePanel);

        bottom = new JPanel();
        bottom.add(new JLabel("Hej"));
        add(bottom, BorderLayout.SOUTH);

        Dimension size = new Dimension(width, height);
        setSize(size);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        pack();
        setVisible(true);

        validate();
        repaint();
    }

    class SpritePanel extends JPanel {

        private static final long serialVersionUID = 1L;
        private ImageIcon background;
//private ArrayList<Sprite> sprites = new ArrayList<Sprite>();

        public SpritePanel(String bgPath) {
            background = new ImageIcon(SpritePanel.class.getResource(bgPath));
            setLayout(null);
            Dimension size = new Dimension(background.getIconWidth(), background.getIconHeight());
            setPreferredSize(size);
            setMaximumSize(size);
            setMinimumSize(size);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(background.getImage(), 0, 0, this);
            System.out.println("painted panel");
        }
    }
}

边注

  • 无需setSize()。您已经 pack()。最好还是打包。
  • pack() 放在 setLocationRelativeTo() 之前。如果您pack() 之后,您会注意到您的框架不会位于所需位置。
  • Event Dispatch Thread (EDT) 运行您的 Swing 应用程序像这样

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                new World("Hej", "/resources/stackoverflow5.png", 1024, 768);
            }
        });
    }
    
  • 如果您想让框架填满屏幕,请不要设置尺寸。不同的机器有不同的屏幕尺寸。而是使用 setExtendedState(JFrame.MAXIMIZED_BOTH);

  • 此外,您的 setSize() 无论如何都不会工作,因为您在 之后调用 pack()

关于java - 我的 JFrame 没有显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21382726/

有关java - 我的 JFrame 没有显示任何内容的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  3. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  4. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  5. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  6. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  7. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  8. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  9. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  10. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

随机推荐