如何从其他类更新JLabel?

时间:2014-07-08 03:38:35

标签: java swing jlabel

我正在尝试从其他类更新JLabel,但它不起作用。 这是两个类。

第一个是通过调用方法showGUI加载GUI的主类。 JLabel在此方法中定义。 此方法还调用第二个类grabScreen,后者需要更新第一个类中的JLabel

MAGNIFY

public class magnify extends JFrame{
    public final void showGUI(){
      JLabel IL = new JLabel(new ImageIcon());
      panel.add( IL );
      IL.setLocation( 0, 0 );

          int[] a= { 11, 20 };
      grabScreen g= new grabScreen( a );

    } 
//showGUI ends here

   public magnify(){  showGUI(); }

   public static void main( String[] args ){
    SwingUtilities.invokeLater( new Runnable(){ public void run(){ magnify rm= new magnify(); rm.setVisible(true); } });
   } 
//main ends here

}
 //magnify class ends here

grabScreen

//Second class grabScreen

public class grabScreen  implements Runnable{
   public grabScreen( int[] a ){
    try{
      IL.setIcon( new ImageIcon(ImageIO.read( new File( "sm.jpeg"  ) ) ) );
      // IL is the JLabel in the first class "magnify" inside a method "showGUI"
    }catch(Exception e ){  }

   }
} 
// grabScreen ends here

1 个答案:

答案 0 :(得分:0)

IL似乎是showGUI方法中定义的局部变量。您可以将其声明为magnify类中的(公共或私有)字段。在grabScreen内,您需要能够访问您已创建的magnify实例(通过将其作为参数传递,或将其分配到grabScreen中的字段)

例如:

public class magnify extends JFrame{
    public JLabel IL;  // <-- THE RELEVANT CHANGE

    public final void showGUI(){
      IL = new JLabel(new ImageIcon());
      panel.add( IL );
      IL.setLocation( 0, 0 );

          int[] a= { 11, 20 };
      grabScreen g= new grabScreen( a, this );

    } 
//showGUI ends here

   public magnify(){  showGUI(); }

   public static void main( String[] args ){
    SwingUtilities.invokeLater( new Runnable(){ public void run(){ magnify rm= new magnify(); rm.setVisible(true); } });
   } 
//main ends here

}
 //magnify class ends here


//Second class grabScreen

public class grabScreen  implements Runnable{
   public grabScreen( int[] a, magnify myMagnify ){ // <-- CHANGE THIS
    try{
      myMagnify.IL.setIcon( new ImageIcon(ImageIO.read( new File( "sm.jpeg"  ) ) ) );
      // IL is the JLabel in the first class "magnify" inside a method "showGUI"
    }catch(Exception e ){  }

   }
} 
// grabScreen ends here

作为样式建议,Java的常规约定规定类应该在CamelCase中命名(以大写字母开头),变量应以小写字母开头;因此magnify应命名为MagnifygrabScreen应命名为GrabScreenIL应命名为il(或更具描述性的内容)

相关问题