2015-10-14 93 views
0

我是新来的编码,我有这个问题:我想添加一个JLabelJFrame我创建在不同的类。这是代码。我不明白如何正确地做到这一点,但如果他们采用相同的方法,我会知道该怎么做。如何将JLabel添加到另一个类的JFrame上?

地图:

import javax.swing.JFrame; 

public class Map { 

    public static void main(String[] args) { 
     map(); 

    } 

    private static void map() { 
     JFrame window = new JFrame("Run Kitty Run!"); 
     window.setVisible(true); 
     window.setSize(1000, 500); 

    } 

} 

猫:

import javax.swing.ImageIcon; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

public class Cat 
{ 
    //instance variables 
    ImageIcon pic; 

    public Cat() 
    { 
     //constructor 
     pic = new ImageIcon("/Users/dell/Desktop/runKittyRun/cat.png"); 

    } 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
    } 

    public void draw() 
    { 
     JPanel panel = new JPanel(); 
     JLabel label = new JLabel(pic); 
     panel.add(label); 
     panel.setVisible(true); 
    } 

} 

我试图做windows.add(标签),并没有工作..:/

+0

这对你来说太过先进,因为你刚刚开始。所需要的只是Map的一个实例。 –

回答

1

简短的回答是,不要,有点......

你有两个基本的选择,你可以允许Cat提供所需对于Map信息来决定谁最应该被显示,例如,有一个getter返回图像

或者,你可以设计Cat所以它很容易可添加到Map

public class Cat extends JPanel 
{ 
    //instance variables 
    ImageIcon pic; 

    public Cat() 
    { 
     //constructor 
     // Absolute file references are a bad idea by the way 
     pic = new ImageIcon("/Users/dell/Desktop/runKittyRun/cat.png"); 
     setLayout(new BorderLayout()); 
     JLabel label = new JLabel(pic); 
     add(label); 
    } 

} 

然后,只需创建一个实例的Cat当你需要它,把它添加到你想要什么都容器......

import java.awt.EventQueue; 
import javax.swing.JFrame; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class Map { 

    public static void main(String[] args) { 
     new Map(); 
    } 

    private static void map() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new Cat()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 
} 
0

确定这算个任何变量或方法,而不仅仅是一个JLabel。首先调用这些方法methodOne和methodTwo。 methodOne将是在一个叫做一个(我不会打扰写出类体,我是从我的iPod这样做)

JLabel jl; 
public void methodOne(){ 
    jl = // blah blah blah; 
} 

好了类,所以现在要在第二个方法使用JL。所以这里是做什么:

public void methodTwo(){ 
    One o = new One(); 
    JFrame j = // instance of JFrame; 
    j.add(o.jl); 
} 

记住:JLabel变量是在类一,所以我实例化一个。

希望有帮助