我有一个程序,里面有JFrame和JInternalFrames。因此,当我尝试使用此代码设置背景时:
BufferedImage myImage;
myImage = ImageIO.read(new File("C:/5/JavaLibrary2/background.jpg"));
ImagePanel Image = new ImagePanel(myImage);
frame.setContentPane(Image);
我的JInternalFrames刚刚消失了。因此,请参见简短的video with debug
frame.setContentPane(Image);只需删除我的JInternal窗口即可。
最佳答案
我没问题
我同时使用了JLabel
和自定义绘制例程。
在将内部框架添加到桌面之前,我已经创建并设置了内部框架,
我已将内部框架添加到桌面,然后更改了其内容窗格,并将更新内容扔到了EDT的末尾,以确保该主框架可见。
问题一定出在您未向我们展示的代码的某些部分。
public class TestInternalFrame {
public static void main(String[] args) {
new TestInternalFrame();
}
public TestInternalFrame() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JDesktopPane desktop = new JDesktopPane();
final JInternalFrame frame1 = new JInternalFrame("Image on Label");
// frame1.setContentPane(new LabelImagePane());
// frame1.pack();
// frame1.setLocation(0, 0);
frame1.setVisible(true);
desktop.add(frame1);
final JInternalFrame frame2 = new JInternalFrame("Painted Image");
// frame2.setContentPane(new ImagePane());
// frame2.pack();
// frame2.setLocation(frame1.getWidth(), 0);
frame2.setVisible(true);
desktop.add(frame2);
JFrame frame = new JFrame("I Haz Images");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(desktop);
frame.setSize(800, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame1.setContentPane(new LabelImagePane());
frame1.pack();
frame1.setLocation(0, 0);
frame2.setContentPane(new ImagePane());
frame2.pack();
frame2.setLocation(frame1.getWidth(), 0);
}
});
}
});
}
public class LabelImagePane extends JPanel {
public LabelImagePane() {
setLayout(new BorderLayout());
JLabel label = new JLabel();
add(label);
try {
label.setIcon(new ImageIcon(ImageIO.read(new File("..."))));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ImagePane extends JPanel {
private BufferedImage image;
public ImagePane() {
try {
image = ImageIO.read(new File("..."));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(), image.getHeight());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int x = (getWidth() - image.getWidth()) / 2;
int y = (getHeight() - image.getHeight()) / 2;
g.drawImage(image, x, y, this);
}
}
}
}