我正在尝试将图片添加到 JTabbedPane 的第一个选项卡,这是我的代码:
JTabbedPane application = new JTabbedApplication();
JPanel welcomePanel = new JPanel();
JLabel imageLabel = new JLabel(new ImageIcon("track.jpg"));
welcomePanel.add(imageLabel);
application.addTab("WELCOME", welcomePanel);
application.setMnemonicAt(0, KeyEvent.VK_1);
图像文件与此代码所在的类位于同一位置。但是,由于某种原因,我的图像没有出现。我使用了相同的 JLabel 并使用文本而不是图像,它就出现了。有人可以给我一些关于这个问题的见解吗?
最佳答案
Java 不知道图像直接位于正在运行的类文件旁边。您必须提交绝对路径。这意味着路径+文件名。
这段小代码将帮助您告诉 Java 该图像位于当前工作目录中。
String file = new File("track.jpg").getAbsolutePath();
添加到您的代码片段中,它看起来像这样:
JTabbedPane application = new JTabbedPane();
JPanel welcomePanel = new JPanel();
String file = new File("track.jpg").getAbsolutePath();
JLabel imageLabel = new JLabel(new ImageIcon(file));
welcomePanel.add(imageLabel);
application.addTab("WELCOME", welcomePanel);
关于java - 将 ImageIcon 添加到 JTabbedPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43377786/