为什么这里没有显示图像?
Why isn`t the image shown here?
我想通过 JLabel 在 JFrame 上显示图像,但唯一显示的是 JFrame。请用新手说出来 :)
这是代码:
import javax.swing.*;
import java.awt.*;
public class Swing extends JFrame{
public JLabel label;
public ImageIcon image;
public Swing() {
setLayout(new FlowLayout());
image = new ImageIcon ("image.png");
label = new JLabel (image);
add(label);
}
public static void main (String [] args) {
System.out.println("some text.");
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(2300, 1717);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(300, 100);
frame.setTitle("title");
frame.requestFocus();
frame.addKeyListener(new KeyHandler());
}
}
图像没有显示,因为你没有告诉你的程序显示它。
在 java 中,函数 main 包含您的计算机将 运行 编译的内容。
我会按照与您相同的方式定义图像,但将图像定义到 main 中,重要的部分是告诉您的程序显示它。
试试这个:
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon("image.jpg");
JLabel label = new JLabel(icon);
frame.add(label);
frame.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
希望对您有所帮助,
可能不是这个
JFrame frame = new JFrame();
你想要这个
JFrame frame = new Swing();
我想通过 JLabel 在 JFrame 上显示图像,但唯一显示的是 JFrame。请用新手说出来 :) 这是代码:
import javax.swing.*;
import java.awt.*;
public class Swing extends JFrame{
public JLabel label;
public ImageIcon image;
public Swing() {
setLayout(new FlowLayout());
image = new ImageIcon ("image.png");
label = new JLabel (image);
add(label);
}
public static void main (String [] args) {
System.out.println("some text.");
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(2300, 1717);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(300, 100);
frame.setTitle("title");
frame.requestFocus();
frame.addKeyListener(new KeyHandler());
}
}
图像没有显示,因为你没有告诉你的程序显示它。
在 java 中,函数 main 包含您的计算机将 运行 编译的内容。
我会按照与您相同的方式定义图像,但将图像定义到 main 中,重要的部分是告诉您的程序显示它。
试试这个:
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon("image.jpg");
JLabel label = new JLabel(icon);
frame.add(label);
frame.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
希望对您有所帮助,
可能不是这个
JFrame frame = new JFrame();
你想要这个
JFrame frame = new Swing();