【发布时间】:2018-04-04 17:31:13
【问题描述】:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class Test extends JPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
constructGUI();
}
});
}
private static void constructGUI() {
JFrame frame = new JFrame("Testy");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.DARK_GRAY);
centerPanel.setPreferredSize(new Dimension(100, 400));
frame.add(centerPanel, BorderLayout.CENTER);
Test eastPanel = new Test();
frame.add(eastPanel, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
public Test() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
Dimension d = new Dimension(50, 50);
JButton button1 = new JButton("");
button1.setPreferredSize(d);
button1.setIcon(new ImageIcon(this.getClass().getResource("/Pictures/ellipse.png")));
button1.setMaximumSize(new Dimension(Integer.MAX_VALUE, button1.getMinimumSize().height));
add(button1);
JButton button2 = new JButton("");
button2.setPreferredSize(d);
button2.setIcon(new ImageIcon(this.getClass().getResource("/Pictures/ellipse.png")));
button2.setMaximumSize(new Dimension(Integer.MAX_VALUE, button2.getMinimumSize().height));
add(button2);
JButton button3 = new JButton("");
button3.setPreferredSize(d);
button3.setIcon(new ImageIcon(this.getClass().getResource("/Pictures/ellipse.png")));
button3.setMaximumSize(new Dimension(Integer.MAX_VALUE, button3.getMinimumSize().height));
add(button3);
add(Box.createVerticalGlue());
}
}
在我的程序中,我试图将椭圆图片放在所有按钮的顶部。正如您在我发布的图片中看到的那样,ellipse.png 位于“图片”源文件夹中。
但是,由于某种原因,图像没有出现在 JButtons 上。
我已经阅读了很多帖子,但我找不到解决问题的方法。
另外,这里是实际椭圆图片的链接:
https://maxcdn.icons8.com/Share/icon/Editing//ellipse_stroked1600.png
【问题讨论】:
-
我不是 Eclipse 用户,但根据您项目的布局和错误消息,我会说
Pictures不包含在应用程序的类路径上下文中。您可以尝试将应用导出为 Jar 并提取内容以仔细检查包含的内容 -
@MadProgrammer 我进行了编辑。程序运行但椭圆图片没有出现在任何按钮上
-
我也建议不要弄乱按钮的尺寸,任何 Swing 组件都不会缩放图像
-
更改图片大小以满足您的要求
-
要么使用图像编辑器,要么在运行时缩放它们——第一个选项几乎总是更好
标签: java eclipse swing jpanel jbutton