java - 无法从扩展的 JPanel 类中看到 ImageIcon
问题描述
我有一个扩展 JPanel 的类,我希望它显示一个 ImageIcon。有些事情似乎没有通过。找到 map.png 并且当我在类中打印出它的大小时是正确的。另外,我将面板设置为黑色,所以我知道面板可以工作,但 ImageIcon 不能。
但是,当我将 TestPanel.java 中的相同代码放入 GUI.java 的构造函数中时,ImageIcon 可以工作。
有人能告诉我为什么 ImageIcon 在 TestPanel.java 中不起作用但在 GUI.java 中起作用吗?
这是我的代码
测试面板.java
public class TestPanel extends JPanel {
public static JLabel map = new JLabel();
public TestPanel() {
this.setLayout(null); //to prevent icon from taking the whole screen
this.setVisible(true); //make frame visible
this.setBounds(0, 0, 100, 100);
this.setBackground(new Color(0,0,0));
Image imageToScale = new ImageIcon("map.png").getImage();
double scale = .9; //scale
int x = (int) (imageToScale.getWidth(null) * scale); //leave image observer as null because we know that the image is loaded
int y = (int) (imageToScale.getHeight(null) * scale);
Image scaledImage = imageToScale.getScaledInstance( x, y, java.awt.Image.SCALE_SMOOTH); //scale the image
ImageIcon image = new ImageIcon(scaledImage); //case the image into an image icon
this.setBounds(0, -4, image.getIconWidth(), image.getIconHeight()); //set position and size of panel to the size of the image. -4 on the Y position because it was not aligned with the top
map.setIcon(image); //set icon for map label
this.add(map); //add label to panel
}
}
图形用户界面.java
public class GUI extends JFrame {
public static JPanel problemPanel = new JPanel(); //panel where the points and path will be displayed
public static JLabel map = new JLabel();
public static TestPanel test = new TestPanel();
public GUI() {
this.setLayout(null); //to prevent icon from taking the whole screen
this.add(test);
//Frame
this.setVisible(true); //make frame visible
this.setSize(1200,1000); //set frame size
this.setTitle("Travelling Apache Pizza Delivery Driver Problem (TAPDDP)"); //set title of panel
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE); //terminates program when frame is closed
this.setLocationRelativeTo(null); //open frame in the middle of the screen
this.setResizable(false); //prevent resizing of GUI
}
}
解决方案
this.setLayout(null);
我通过在TestPanel
类中删除来修复代码。
推荐阅读
- python - matplotlib savefig 导致分段违规
- python - Python正则表达式:使用findall仅从括号中提取整数的问题
- java - Spring 将数据保存到数据库时,一切都为空
- ios - AudioKit 引擎在物理设备上失败错误域=com.apple.coreaudio.avfaudio 代码=-10875
- javascript - event.isTrusted 可以信任吗?
- r - 如何使用传单设置边界并使用 mapshot 导出为 pdf?
- android - 是否仅为公共属性创建了支持属性?
- jstl - 我试图在 jstl 的帮助下使用 sql 但遇到异常
- php - 对加密的 PHP 对象进行排序
- ios - 无法从 Spring Boot 向 FCM 和远程用户发送推送通知?