首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从不同的类更新JLabel?

如何从不同的类更新JLabel?
EN

Stack Overflow用户
提问于 2014-07-08 03:38:35
回答 1查看 122关注 0票数 0

我正在尝试从不同的类更新一个JLabel,但是它不起作用。这是两个班。

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

放大

代码语言:javascript
复制
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

代码语言:javascript
复制
//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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-08 03:42:21

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

例如:

代码语言:javascript
复制
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 (或者更具有描述性的东西)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24623297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档