一段时间以来,我一直在努力让图像显示出来。我读了一些不同的东西,它们似乎都有不同的显示图像的方式。有人可以告诉我我做错了什么吗?我正在尝试制作一个程序,该程序使用 2 个类来使图片显示在框架中。我想我仍然不明白的是什么是 Graphics 对象,什么是 Graphics2D 对象,它有何不同,以及我调用什么类的什么方法来显示图像。这是我的代码:
公共(public)课笑脸{
private BufferedImage smileyFace;
private Graphics2D renderWindow;
private Dimension smileyPosition;
private File smileyFile;
public Smiley() {
try{
smileyFile = new File("C:\\Users\\MyName\\Desktop\\smiley.png");
smileyFace = ImageIO.read(smileyFile);
}
catch (Exception e){
System.out.println("There was an error finding or reading the file \" smiley.png.\"");
}
MainScreen.graphicPane.drawImage(smileyFace,50,50, null);
}
第二类:
公共(public)类 MainScreen 扩展 JFrame{
public static MainScreen ms;
public static Graphics2D graphicPane;
public static void main (String[] args){
MainScreen ms = new MainScreen();
Smiley newSmiley = new Smiley();
}
public MainScreen(){
super("Main Screen Window");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
this.setSize(500,800);
this.getContentPane().setBackground(Color.black);
graphicPane = (Graphics2D) this.getContentPane().getGraphics();
}
程序编译没有错误,也没有任何关于找不到文件的报告。
最佳答案
您将需要一些paint
方法。为此,您将需要一个组件来进行绘制。你需要学习一个 GUI 框架,比如 Swing。您可以在一些清晰的组件上绘画,例如 JPanel
。对于该面板,您需要覆盖其 paintComponent
方法。
Graphcics
对象是组件用来将图形实际绘制到组件上的对象。
Graphics2D
对象只是扩展了 Graphics 对象的功能。
你应该看看 Swing tuorial和 **Graphics toturial
虽然你会做这样的事情让你的程序运行
public class DrawPanel extends JPanel {
BufferedImage smileyFace;
public DrawPanel() {
try{
smileyFile = new File("C:\\Users\\MyName\\Desktop\\smiley.png");
smileyFace = ImageIO.read(smileyFile);
}
catch (Exception e){
System.out.println("There was an error finding or reading the file \" smiley.png.\"");
}
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(smileyFace,50,50, this);
}
@Override
public Dimension getPreferredSize(){
return new Dimension(500, 500);
}
}
然后您可以在另一个类中实例化该面板,将其添加到 JFrame 中以运行它
public class Main {
public static void main(String[] args) {
SwingUtiliites.invokeLater(new Runnable(){
public void run() {
JFrame frame = new JFrame();
frame.add(new DrawPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
关于java - 在 Java 中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21045119/