简体   繁体   English

在Java程序中向窗口添加png图像的最简单方法是什么?

[英]What is the simplest way to add a png image to a window in my Java program?

Background 背景

I have a class for a graphical representation of a die, and a switch statement where each case accounts for the user inputting a value 1 - 6, each case doing a method to draw respective dots on the die. 我有一个用于模具图形表示的类,以及一个switch语句,其中每种情况都说明用户输入的值是1-6,每种情况都在做一种在模具上绘制各个点的方法。

** My Question ** ** 我的问题 **

I need the default to display text saying something to the extent of "Invalid entry" for 0 or >6, but if I wanted to also display a png image on the die when invalid, how do I go about this? 我需要使用默认值来显示文本,以表示“无效输入”的范围为0或> 6,但是如果我想在无效时在模具上也显示png图像,该如何处理?

I am new to Java, so I need to know what methods or classes I may need to import/use to add in a picture, and I'd also like to know where I should save the image 我是Java的新手,所以我需要知道可能需要导入/使用哪些方法或类才能添加图片,并且我还想知道应该将图像保存在哪里。

I do not have a src folder under my Java Project, it's weird, and I do not have a bin, which I've heard of before. 我的Java项目下没有src文件夹,这很奇怪,并且我没有以前曾听说过的bin。 If necessary, I can copy the files into a new, well-setup java project. 如有必要,我可以将文件复制到一个设置正确的新Java项目中。

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.*;
import javax.swing.ImageIcon;
import java.awt.Image;


public class PictureBox
{

   public JFrame f = new JFrame();
   public JButton b = new JButton();

   public PictureBox()
   {

      f.setUndecorated(true);
      f.setSize(50, 50);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setLocation((200), (200));


      ImageIcon pic = new ImageIcon("pic.png");
      Image icon = pic.getImage();
      Image real = icon.getScaledInstance(50, 50, java.awt.Image.SCALE_SMOOTH);
      //For the 50's, put in the actual dimensions you want the picture to be
      pic = new ImageIcon(real);

      b.setIcon(pic);

      f.add(b);
      f.setVisible(true);
      f.setEnabled(false);

   }

   public static void main(String[] args)
   {

      PictureBox pb = new PictureBox();

   }

}

This will do the plain and simple of setting up an image. 这将简单而简单地设置图像。 I don't know how your program is implemented so edit in whatever way you need it to. 我不知道您的程序是如何实现的,所以请按您需要的任何方式进行编辑。

Now as for where the picture goes, depending on the IDE (I use JGrasp), you may just need to toss it in the same folder as the class. 现在关于图片的位置,取决于IDE(我使用JGrasp),您可能只需要将它扔到与类相同的文件夹中即可。 This is not organized in the slightest, but it will most likely work for the moment. 这不是一丁点的组织,但目前很可能会起作用。

Also pic.png is the name my picture is called, enter in the name of your picture 同样pic.png是我的图片的名称,请输入图片的名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM