Nick Nick - 2 months ago 11
Java Question

How to add a JButton to JFrame from other class

am trying to add a button to Jframe from other class but it does not work

public class ShowMain {


public static void main(String[] args) throws Throwable {


//My JFrame
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setLayout(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.GRAY);
}


My other Class

public class Commands {

public static void main(String[] args) throws Throwable {
//JButtons
JButton button1 = new JButton();
button1.setText("");
button1.setBounds(120, 350, 400, 20);
button1.setVisible(true);
}


frame.add(button1) is not working

Answer

You've got all your code within two static main methods, meaning that the two classes can hardly interact at all. I suggest that you create true OOP-compliant classes, with instance fields ("state"), instance methods ("behavior"), and that you have one class call the method of another if you wish to change its state. For instance, if the Commands class is to add a JButton, then give your ShowMain class a method for this: public void addCommandButton(JButton button).

Having said this, I wouldn't do this at all if this were my code, but rather would follow a more MVC or "Model-View-Controller" program structure, where one set of classes would represent the program logic, another the user interactions (the listeners) and a 3rd set of classes for the GUI or "view".

For example, run this code that shows how to connect classes without them knowing about the other class (loose coupling):

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class ShowMain {
    private static void createAndShowGui() {
        MainPanel mainPanel = new MainPanel();
        JScrollPane scrollPane = new JScrollPane(mainPanel);
        CreateActionPanel actionPanel = new CreateActionPanel();
        new Controller(actionPanel, mainPanel);

        JFrame frame = new JFrame("ShowMain");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(actionPanel, BorderLayout.PAGE_START);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

class MainPanel extends JPanel {
    private static final int PREF_W = 400;
    private static final int PREF_H = 80;

    @Override
    public Dimension getPreferredSize() {
        Dimension superSz = super.getPreferredSize();
        if (isPreferredSizeSet()) {
            return superSz;
        }
        int prefW = Math.max(superSz.width, PREF_W);
        int prefH = Math.max(superSz.height, PREF_H);
        return new Dimension(prefW, prefH);
    }

    public MainPanel() {
        setBorder(BorderFactory.createTitledBorder("Main Panel"));
    }

    public void addButtonAction(Action action) {
        add(new JButton(action));

        // so the button will be displayed properly
        revalidate();
        repaint();
    }
}

class Controller {
    public Controller(final CreateActionPanel actionPanel, final MainPanel mainPanel) {
        actionPanel.addPropertyChangeListener(CreateActionPanel.ACTION_NAME, pcEvt -> {
            mainPanel.addButtonAction(new AbstractAction((String) pcEvt.getNewValue()) {
                {
                    int mnemonic = (int) pcEvt.getNewValue().toString().charAt(0);
                    putValue(MNEMONIC_KEY, mnemonic);
                }

                @Override
                public void actionPerformed(ActionEvent evt) {
                    System.out.printf("Button %s pressed!%n", evt.getActionCommand());
                }
            });
        });
    }
}

class CreateActionPanel extends JPanel {
    public static final String ACTION_NAME = "action name";
    private JTextField actionNameField = new JTextField(10);

    public CreateActionPanel() {
        actionNameField.addActionListener((e -> {
            String text = actionNameField.getText();
            firePropertyChange(ACTION_NAME, null, text);
            actionNameField.selectAll();
        }));

        add(new JLabel("Button Text to Add:"));
        add(actionNameField);
    }
}
Comments