我正在尝试创建一个看起来像扑克牌的切换按钮。无论我将 img 文件夹放在哪里,都无法显示图像。我正在使用以下代码。
final JFrame frame = new JFrame("Toggle button test");
frame.setSize(500, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane( ).setLayout(new FlowLayout());
ImageIcon icon = new ImageIcon("img/1.png");
JToggleButton jtbButton = new JToggleButton(icon);
frame.add(jtbButton);
frame.setVisible(true);
最佳答案
添加以下内容
System.out.println(new File("img/1.png").getAbsolutePath());
然后确保文件夹 img
存在于显示的位置
旁白:通常您会希望从类路径读取图像资源,而不是依赖于文件位置。这就是为什么最好从资源中读取,例如:
ImageIcon icon = new ImageIcon(MyClass.class.getResource("img/1.png"));
关于java - 带图标的切换按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17528951/