修改
我提交了以下错误(虽然可能需要几天才能获得批准): http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7043319
更多细节:
我想要的是制作一个背景图像面板,在其上面有额外的面板(附加组件 - 例如JButton,自定义形状等 - 并在其中)并正确地绘制所有这些。我在我的应用程序中使用JLayeredPane用于此目的,但为了示例,下面的代码应该足够了。无论以下问题如何,我都乐于接受有关如何做我想做的建议。
我遇到的问题是这幅画表现得非常奇怪。它没有完全重新绘制(例如,只有图像上方的顶部),它重新绘制 - 从我注意到越来越多的间隔 - 步骤(例如第一涂料,第三涂料,第九涂料,第21涂料,第64涂料等)。 )。我的猜测是我在这里实施太多了 - 下面有什么明显的错误吗?
另外,下面有三条注释行。有趣的是,取消注释任何一个并评论以下行解决了这个问题。图像具有以下属性(似乎哪个图像 - 只是尺寸无关紧要):
cat.jpg JPEG 640x533 640x533+0+0 8-bit DirectClass 110KB 0.000u 0:00.000
cat-small.jpg JPEG 200x167 200x167+0+0 8-bit DirectClass 7.99KB 0.000u 0:00.000
以下是我遇到问题的Java代码:
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class SwingDrawingPrb {
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
final JFrame frame = new JFrame("SwingDrawingPrb");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Container contentPane = frame.getContentPane();
frame.setLocation(550, 50);
frame.setSize(1000, 800);
frame.setVisible(true);
// ImageIcon image = new ImageIcon(SwingDrawingPrb.class.getResource("/cat-small.jpg"));
ImageIcon image = new ImageIcon(SwingDrawingPrb.class.getResource("/cat.jpg"));
final JPanel imagePanel = new JPanel() {
// Color trans = new Color(255, 0, 0, 255);
Color trans = new Color(255, 0, 0, 64);
protected void paintComponent(Graphics g) {
System.out.println("painting");
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(trans);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.blue);
g.drawLine(0, 0, 1000, 1000);
}
};
imagePanel.setBounds(0, 0, image.getIconWidth() + 200, image.getIconHeight() + 200);
imagePanel.setLayout(null);
// JLabel imageLabel = new JLabel("Hello, world!");
JLabel imageLabel = new JLabel(image);
imageLabel.setBounds(100, 100, image.getIconWidth(), image.getIconHeight());
imageLabel.addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
System.out.println("mouseMoved");
imagePanel.repaint();
}
});
imagePanel.add(imageLabel);
contentPane.add(imagePanel);
}
}