第一个JFrame有一个JLabel,上面有一张背景图片,还有一个鼠标控制大小的矩形框;
在第二个JFrame里显示矩形框内的部分背景图片。
对于这样的问题,大大们会怎么去处理?我说说自己的处理方式:
class FirstLabel extens JLabel implements MouseMotionListener{
private Image selectedImg;
private int selectedWidth,selectedWidth;
private SecondLabel secondLabel;
public FirstLabel(){
...
JFrame secondFrame=new JFrame();
secondLabel=new SecondLabel();
secondFrame.add(secondLabel);
}
...
public void paintComponent(){
...
selectedWidth=...;//get new width
selectedHeight=...;//get new height
selectedImg=...;//get new image
secondLabel.repaint();//repaint the image of second label
}
...
private class SecondLabel extends JLabel{
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(selectedImg,0,0,selectedWidth,selectedHeight,null);
}
}}问题:
当第一个JLabel中的矩形大小变化的时候,第二个JLabel中的图像并没有跟着变化;如果我把第二个JFrame最大化,那么图像就会得到更新,这样显然是不对的。怎么样才能使第二个JLabel中的图像跟随第一个JLabel中的矩形的变化而变化呢?
在第二个JFrame里显示矩形框内的部分背景图片。
对于这样的问题,大大们会怎么去处理?我说说自己的处理方式:
class FirstLabel extens JLabel implements MouseMotionListener{
private Image selectedImg;
private int selectedWidth,selectedWidth;
private SecondLabel secondLabel;
public FirstLabel(){
...
JFrame secondFrame=new JFrame();
secondLabel=new SecondLabel();
secondFrame.add(secondLabel);
}
...
public void paintComponent(){
...
selectedWidth=...;//get new width
selectedHeight=...;//get new height
selectedImg=...;//get new image
secondLabel.repaint();//repaint the image of second label
}
...
private class SecondLabel extends JLabel{
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(selectedImg,0,0,selectedWidth,selectedHeight,null);
}
}}问题:
当第一个JLabel中的矩形大小变化的时候,第二个JLabel中的图像并没有跟着变化;如果我把第二个JFrame最大化,那么图像就会得到更新,这样显然是不对的。怎么样才能使第二个JLabel中的图像跟随第一个JLabel中的矩形的变化而变化呢?
第一个JFrame里有第二个JFrame的引用,
第二个JFrame里写一个Public方法根据传入的Image对象重画图像,
第一个里的图象改变后将图像的Image对象作为参数传入第二个JFrame的Public方法。
程序刚开始运行,本来第二个JFrame应该显示默认的图片,可是没有。只有把第二个JFrame最大化最后才可以看到默认的图片。
程序运行过程中,缩放矩形的大小,有时候,第二个JFrame中部分象素没有刷新,最有把它最大化之后才会得到刷新。
问题是,每次矩形变化之后,我都repaint第二个JFrame的图像的啊?
太诡异了!一点想法都没有。大大们帮帮忙啊!
现在我把第二个显示窗口的尺寸固定了,不再跟随矩形的变化而改变,就能够正常的显示图像了。