简体   繁体   中英

Why 'JPanel' isn't working?

The panel.add() is red for some mysterious reason. The panel is initialized right above!

public class ShowImage {

    ImageIcon image = new ImageIcon("D:/java.jpg");
    JLabel label = new JLabel("sdasd", image, JLabel.CENTER);
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(label, BorderLayout.CENTER);  
}

You cannot invoke a method directly in class. I believe you want to invoke that in constructor.

public class ShowImage {
    ImageIcon image = new ImageIcon("D:/java.jpg");
    JLabel label = new JLabel("sdasd", image, JLabel.CENTER);
    JPanel panel = new JPanel(new BorderLayout());

    public ShowImage (){
        panel.add(label, BorderLayout.CENTER);
    }
}

You need to put all this code(or atleast the panel.add statement) inside a method. You can't just let that piece of code hang around in the class anywhere. Calling a method just anywhere in the class is not allowed in Java.

You can probably put it in the constructor or some init method.

public class ShowImage {
    ImageIcon image = new ImageIcon("D:/java.jpg");
    JLabel label = new JLabel("sdasd", image, JLabel.CENTER);
    JPanel panel = new JPanel(new BorderLayout());

    public void someInitMethod() { // or even the constructor
        panel.add(label, BorderLayout.CENTER);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM