Carol.Kar
Carol.Kar

Reputation: 5355

Add method to frame.add()

I want to load the method mainWindow() in frame.add(). However, I get the exception:

mainWindow cannot be resolved to a type because it is not from the type component.

public class MainWindow {

    private static final Logger log = Logger.getLogger(MainWindow.class);

    public void mainWindow() {

        log.info("enter mainWindow method");

        MigLayout layout = new MigLayout("fillx", "[right]rel[grow,fill]", "[]10[]");
        JPanel panel = new JPanel(layout);

        panel.add(new JLabel("Enter size:"),"");
        panel.add(new JTextField(""),"wrap");
        panel.add(new JLabel("Enter weight:"),"");
        panel.add(new JTextField(""),"");

    }

    public void createAndShowGUI() {

        log.info("create and show GUI");

        JFrame frame = new JFrame("FileChooserDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add content to the window.
        frame.add(new mainWindow());

        //Display the window.
        frame.pack();
        frame.setVisible(true);


    }


}

Is there another way to add the mainWindow() method to frame.add(), without changing it into a component?

I appreciate your answer!

Upvotes: 0

Views: 1687

Answers (1)

ethanfar
ethanfar

Reputation: 3778

Change:

public void mainWindow() {

    log.info("enter mainWindow method");

    MigLayout layout = new MigLayout("fillx", "[right]rel[grow,fill]", "[]10[]");
    JPanel panel = new JPanel(layout);

    panel.add(new JLabel("Enter size:"),"");
    panel.add(new JTextField(""),"wrap");
    panel.add(new JLabel("Enter weight:"),"");
    panel.add(new JTextField(""),"");

}

Into:

public JComponent mainWindow() {

    log.info("enter mainWindow method");

    MigLayout layout = new MigLayout("fillx", "[right]rel[grow,fill]", "[]10[]");
    JPanel panel = new JPanel(layout);

    panel.add(new JLabel("Enter size:"),"");
    panel.add(new JTextField(""),"wrap");
    panel.add(new JLabel("Enter weight:"),"");
    panel.add(new JTextField(""),"");

    return panel;
}

Upvotes: 3

Related Questions