我是Java GUI的新手,并且遇到显示图像的问题。我的目的是显示一个大的图像,并允许用户点击图像的区域来指示特定位置的位置。无论如何,尽管读了甲骨文的解释和其他解决方案,我甚至无法让图片出现。显示图像,Java
我创建了一个JFrame并使用它的setContentPane()方法来添加一个JPanel和JLabel。我使用JLabel的setIcon()方法来添加一个图像,或者至少这是我的意图...
任何意见是赞赏,特别是如果有更好的方式做到这一点。我将使用OpenCV处理图像,并计划在显示它们之前将它们转换为Java图像(或BufferedImage)。
这是代码。为了节省空间,我排除了图书馆。
public class Pathology {
public static void main(String[] args) {
PrimaryFrame primaryFrame = new PrimaryFrame();
primaryFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
primaryFrame.setSize(1500, 900);
primaryFrame.setVisible(true);
primaryFrame.setContentPane(primaryFrame.getGui());
try {
primaryFrame.setImage(ImageIO.read(new File("C:\\Users\\Benjamin\\Pictures\\Pathology\\C\\001.png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GUI类:
public class PrimaryFrame extends JFrame{
//private JTextField textField1;
JPanel gui;
JLabel imageCanvas;
public PrimaryFrame() {
super("Pathology-1");
//setLayout(new FlowLayout());
//textField1 = new JTextField("Chup!", 50);
//add(textField1);
}
public void setImage(Image image) {
imageCanvas.setIcon(new ImageIcon(image));
}
public void initComponents() {
if (gui==null) {
gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(5,5,5,5));
imageCanvas = new JLabel();
JPanel imageCenter = new JPanel(new GridBagLayout());
imageCenter.add(imageCanvas);
JScrollPane imageScroll = new JScrollPane(imageCenter);
imageScroll.setPreferredSize(new Dimension(300,100));
gui.add(imageScroll, BorderLayout.CENTER);
}
}
public Container getGui() {
initComponents();
return gui;
}
}
谢谢,LuxxMiner。我仍在努力掌握这些基本原理。 – horseatingweeds