此方法将从 JFrame 获取玻璃窗格,该引用存储在 JPanel 对象中,我使用 JPanel 对象中的 getGraphics 来获取图形引用,然后尝试为玻璃窗格绘制背景图像,当我运行此代码时它显示背景图像闪烁,然后图像消失。我尝试了很多方法,例如使用 getClass.getResources(path) 而不是 File 或扩展 JPanel 并设置图像,因为它具有相同的结果。
private void createProfile()
{
gls = (JPanel) mainUi.getGlassPane();
gls.setLayout(new GridBagLayout());
Graphics g = gls.getGraphics();
BufferedImage img=null;
try {
img = ImageIO.read(new File("/data/images/Lighthouse.jpg"));
System.out.println("Hello");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
g.drawImage(img, 0, 0, gls.getWidth()
,gls.getHeight(), null);
//gls.removeAll();
JPanel profileName = new JPanel(new BorderLayout());
JPanel profileTitlePanel = new JPanel(new BorderLayout());
profileTitlePanel.setSize(0, 20);
profileTitlePanel.setBackground(Color.black);
JLabel profileTitleLabel = new JLabel(" Create New Profile ");
profileTitleLabel.setForeground(Color.white);
profileTitleLabel.setFont(getFont(Font.BOLD,20));
profileTitlePanel.add(profileTitleLabel);
profileName.add(BorderLayout.NORTH, profileTitlePanel);
JPanel profileSelection = new JPanel(new GridLayout(5,1));
profileSelection.add(new JPanel());
JLabel nameLabel = new JLabel(" Enter Your Name : ");
Font font = getFont(Font.HANGING_BASELINE,16);
nameLabel.setFont(font);
profileSelection.add(nameLabel);
final JTextField name = new JTextField();
name.setFont(font);
profileSelection.add(name);
profileSelection.add(new JPanel());
JPanel okClear = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JButton ok = new JButton("Ok");
ok.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
File file = new File("data/profiles/"+name.getText()+"/save");
try {
if(!file.exists())
{
file.mkdirs();
new File("data/profiles/"+name.getText()+"/saves.dat").createNewFile();
noProfile=false;
System.out.println("The Current Profile -> "+noProfile);
// mainWindow();
currentProfile = name.getText();
new DataOutputStream(new FileOutputStream("data/state.dat")).writeBoolean(noProfile);
new DataOutputStream(new FileOutputStream("data/current_profile.dat")).writeUTF(currentProfile);
//new DataOutputStream(new FileOutputStream(file)).writeInt(1);
gls.setVisible(false);
mainUi.repaint();
mainWindow();
}
else
{
createProfile();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
okClear.add(ok);
JButton clear = new JButton("Clear");
clear.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
name.setText("");
}
});
okClear.add(clear);
profileSelection.add(okClear);
profileName.add(profileSelection);
GridBagConstraints gbc = new GridBagConstraints();
gbc.ipadx= 10;
gbc.ipady = 10;
profileName.setBorder(BorderFactory.createEtchedBorder());
profileName.setSize(400, 250);
gls.add(profileName,gbc);
gls.setVisible(true);
}