所以我试图将图像添加到我的JFrame中,并且我得到了我使用BorderLayout.PAGE_START,但我不想要灰色背景。有没有办法去除"删除"那个背景还是用另一个布局来做,得到我想要的结果?
*我还要在画面底部添加一些图像,所以我也不想在那里有灰色背景。
编辑: 这是我的代码:
private JFrame getCreatedFrame(){
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(screenSize);
frame.setLocationRelativeTo(null);
JFrame.setDefaultLookAndFeelDecorated(true);
//set icon image
String imgName = "images/domino.png";
URL imageURL = getClass().getResource(imgName);
if (imageURL != null) {
icon = new ImageIcon(imageURL);
}
frame.setIconImage(icon.getImage());
//set background image
imgName = "images/background.jpg";
imageURL = getClass().getResource(imgName);
if (imageURL != null) {
icon = new ImageIcon(imageURL);
}
JLabel background=new JLabel(icon);
frame.add(background);
return frame;
}
public void start() {
short version=0,choice=0;
JFrame frame=getCreatedFrame();
//set welcome image
String imgName = "images/welcome.png";
URL imageURL = getClass().getResource(imgName);
if (imageURL != null) {
icon = new ImageIcon(imageURL);
}
JLabel welcome=new JLabel(icon);
frame.add(welcome,BorderLayout.PAGE_START);
frame.setVisible(true);
}
答案 0 :(得分:1)
建议:
paintComponent(...)
方法覆盖中绘制两个图像。例如:
import java.awt.FlowLayout;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
@SuppressWarnings("serial")
public class WelcomePanel extends JPanel {
public WelcomePanel(Image backGround, Image foreGround) {
JLabel backGroundLabel = new JLabel(new ImageIcon(backGround));
JLabel foreGroundLabel = new JLabel(new ImageIcon(foreGround));
// if you want the welcome image away from the edge, then give
// backGroundLabel an empty border with appropriate insets. For example:
// backGroundLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
backGroundLabel.setLayout(new FlowLayout());
backGroundLabel.add(foreGroundLabel);
}
private static void createAndShowGui() {
String backImgName = "images/domino.png";
String foreImgName = "images/welcome.png";
URL backImageURL = WelcomePanel.class.getResource(backImgName);
URL foreImageURL = WelcomePanel.class.getResource(foreImgName);
Image backGroundImg = null;
Image foreGroundImg = null;
if (backImageURL != null && foreImageURL != null) {
try {
backGroundImg = ImageIO.read(backImageURL);
foreGroundImg = ImageIO.read(foreImageURL);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
WelcomePanel mainPanel = new WelcomePanel(backGroundImg, foreGroundImg);
// or perhaps better to use a JDialog
JFrame frame = new JFrame("Image On Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}