【发布时间】:2016-03-22 06:35:17
【问题描述】:
我有JLayeredPane,它在0级包含Canvas(在Paint方法中填充自己的黄色)和JPanel在1级(在构造函数中将它的背景设置为红色)。
在按钮上单击paintAllToImage 方法我创建BufferedImage 并使用component.paintAll(image.getGraphics()); 在此图像上绘制JLayerePane
问题是,该图像只有Canvas 绘制(它完全填充为黄色)。请看附图。
(按钮上方是实际绘制的,按钮下方是图像,由JLayeredPane创建)
这里是完整的代码:
public class LayeredPaneEx extends JPanel {
private JLayeredPane layeredPane;
public LayeredPaneEx() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(300, 310));
layeredPane.setLayout(null);
Canvas panel = new CustomCanvas();
panel.setSize(300, 400);
CustomPanel customPanel = new CustomPanel();
layeredPane.add(panel, new Integer(0));
layeredPane.add(customPanel, new Integer(1));
add(layeredPane);
JButton paintBtn = new JButton("Paint All");
paintBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon(paintAllToImage(layeredPane));
JLabel imageLabel = new JLabel(icon);
add(imageLabel);
}
});
add(paintBtn);
JLabel paintLabel = new JLabel();
paintLabel.setPreferredSize(new Dimension(300, 300));
}
private class CustomCanvas extends Canvas {
@Override
public void paint(Graphics g) {
g.setColor(Color.YELLOW);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
private class CustomPanel extends JPanel {
CustomPanel() {
setSize(100, 100);
setBackground(Color.RED);
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("LayeredPaneDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new LayeredPaneEx();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static BufferedImage paintAllToImage(Component component) {
BufferedImage image;
image = new BufferedImage(
component.getWidth(),
component.getHeight(),
BufferedImage.TYPE_INT_RGB
);
component.paintAll(image.getGraphics());
return image;
}
}
【问题讨论】:
-
谨防将重量级 (
Canvas) 与重量轻的组件混合在一起。因为 AWT 组件没有 z-ordering 的概念,您会发现这将导致您无穷无尽的问题。此外,您应该更喜欢printAll而不是paintAll
标签: java swing canvas awt jlayeredpane