我正在尝试从不同的类更新一个JLabel,但是它不起作用。这是两个班。
首先是通过调用方法showGUI来加载GUI的主类。JLabel是在此方法中定义的。该方法还调用第二类grabScreen,后者需要更新第一个类中的JLabel。
放大
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 heregrabScreen
//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发布于 2014-07-08 03:42:21
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应该被命名为Magnify,grabScreen应该被命名为GrabScreen,IL很可能应该被命名为il (或者更具有描述性的东西)。
https://stackoverflow.com/questions/24623297
复制相似问题