Search code examples
javajbutton

How to add Jbutton from another class to main class


So am I trying to add JButton from another class into my main class, but I have no idea how to. Do I have to use a certain command or import a package to add the button?

//my first class with JButton
public class ScreenInitial
{
  public ScreenInitial()
  {
    JPanel  panel = new JPanel();
    panel.setLayout(new GridLayout(0, 1));
    JButton newArrival = new JButton("New Arrival");
    panel.add(newArrival);
  }
}



//my main class
public class FurryFriendsAnimalShelter extends JFrame
{ 
  public static void main(String[] args)
  {
    JFrame window = new JFrame("FFAS");
    Toolkit tk = Toolkit.getDefaultToolkit();
    int widthScreen = ((int)tk.getScreenSize().getWidth());
    int lengthScreen = ((int) tk.getScreenSize().getWidth());
    window.setSize(widthScreen,lengthScreen);
    window.getContentPane().setBackground(Color.BLACK);
    window.show(true);
  }
}

Solution

  • The easiest way is to extend some JComponent type and let everything rely on that class.

    public class NewClass {
    
        public static void main(String[] args) {
            JFrame window = new JFrame("Furry Friends Animal Shelter");
            Toolkit tk = Toolkit.getDefaultToolkit();
            int widthScreen = ((int) tk.getScreenSize().getWidth());
            int lengthScreen = ((int) tk.getScreenSize().getWidth());
            window.setSize(widthScreen, lengthScreen);
            window.getContentPane().setBackground(Color.BLACK);
            window.add(new ScreenInitial());
            window.show(true);
        }
    
        public static class ScreenInitial extends JPanel {
    
            public ScreenInitial() {
                setLayout(new GridLayout(0, 1));
                JButton newArrival = new JButton("New Arrival");
                add(newArrival);
            }
        }
    }