I've been trying at this for an hour now and for some reason I can't seem to get my image to show on the JFrame
canvas. I've Googled lots of other questions but none can help. After inputting the image onto the frame I will need to put text over that, but I can do that I just can't seem to get the image shown. Also updated.
import java.util.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Meme extends JPanel{
public BufferedImage img;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Generate();
}
public static void Generate() {
//Creating the frame
JFrame mainframe = new JFrame("Meme");
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setSize(800, 800);
mainframe.setVisible(true);
}
/**
* @param g
*/
@Override
public void paint(Graphics g) {
try {
img = ImageIO.read(new File("pic.jpg"));
g.drawImage(img, 50, 50, this);
} catch (IOException e) {
}
}
}
答案 0 :(得分:0)
呃..这个(短)单一方法有这么多问题:
public void paint(Graphics g) {
try {
img = ImageIO.read(new File("pic.jpg"));
g.drawImage(img, 50, 50, this);
} catch (IOException e) {
}
}
JComponent
(或JPanel
中的扩展名)的正确方法是paintComponent(Graphics)
。Generate
方法(BTW,应为小写首字母,I.E。generate
)} catch (IOException e) { }
上面有人说这看起来很傻' - 因为它是。代码忽略或吞噬那些非常方便的堆栈跟踪,这可能有助于解释直接和最相关的问题。将其更改为} catch (IOException e) { e.printStackTrace(); }
以获取更多信息。我刚注意到其他一些可能是“没有去过”的事情。这个代码。 Generate
方法是从main
方法调用的唯一方法。它决不会创建Meme
并将其添加到框架中!你期望出现在框架中的是什么?
以上代码经过重新设计,包含上述建议以及其他一些建议。 它不会修复所有潜在问题或包含所有可能的优化。
结果如下:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Meme extends JPanel {
public BufferedImage img;
Meme() {
/* This next statement is purely for debugging. If the GUI is not red
inside the frame decorations, something is very wrong. */
setBackground(Color.RED);
try {
//img = ImageIO.read(new File("pic.jpg"));
img = ImageIO.read(new URL("https://i.stack.imgur.com/7bI1Y.jpg"));
generate();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Meme();
}
public void generate() {
//Creating the frame
JFrame mainframe = new JFrame("Meme");
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.add(this);
mainframe.setSize(600, 500);
mainframe.setVisible(true);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 50, 50, this);
}
}