Nick Nick - 2 months ago 13
Java Question

frame add doesn't work to another java file

test.java

import javax.swing.JFrame;

public class test {

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(600, 600);

}

}


My Other java File test2.java

import javax.swing.JButton;

public class test2 {

public static void main(String[] args) {
JButton Button = new JButton();
frame.add(Button);

}

}


am trying to call frame to test2.java

Answer

Try this:

Test.java

public class Test
{
     public static void main(String[] args)
     {
        JFrame frame = new JFrame();
        frame.setVisible(true);
        frame.setSize(600, 600);

        // By passing the frame as a reference, the function
        // will be able to add the button to this frame.
        Test2.addButton(frame);
    }
}

Test2.java

public class Test2 {
    public static void addButton(JFrame frame)
    {
        JButton button = new JButton();
        frame.add(button);
    }
}
Comments