Java Swing. Opening a new JPanel from JButton and creating buttons is pretty

I am trying to create a small program with a basic GUI with two buttons. One button will close the program, the other will open a new JPanel which will have text fields, etc.

I would like to be able to create buttons to look like normal application buttons, nice and square, equal size, etc. I think. etc., I'm not sure how to do this.

Also, I'm not sure how to open a new JFrame using a button.

GUI code:

package practice;

public class UserInterface extends JFrame {

    private JButton openReportSelection = new JButton("Open new Window");
    private JButton closeButton = new JButton("Close Program");

    private JButton getCloseButton() {
        return closeButton;
    }

    private JButton getOpenReportSelection() {
        return openReportSelection;
    }

    public UserInterface() {
        mainInterface();

    }

    private void mainInterface() {
        setTitle("Program Information Application");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel centerPanel = new JPanel(new GridLayout(0, 3));

        centerPanel.add(openReportSelection);
        centerPanel.add(closeButton);
        getCloseButton().addActionListener(new Listener());
        add(centerPanel, BorderLayout.CENTER);
        setSize(1000, 200);
        setVisible(true);
    }

    private void addReportPanel() {
        JPanel reportPanel = createNewPanel();
        getContentPane().add(reportPanel, BorderLayout.CENTER);

    }

    private JPanel createNewPanel() {
        JPanel localJPanel = new JPanel();
        localJPanel.setLayout(new FlowLayout());
        return localJPanel;
    }

}

      

ActionListener class code:

package practice;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Listener implements ActionListener {


    public void actionPerformed(ActionEvent ae) {       
           System.exit(0);
    }    



}

      

EDIT: I think opening a new JPanel is the way to go, not a JFrame. What would be the best way to do this from a Jbutton click?

+2


source to share


4 answers


Start by using a different layout manager, FlowLayout

or GridBagLayout

might work better

JPanel centerPanel = new JPanel(new FlowLayout());
centerPanel.add(openReportSelection);     
centerPanel.add(closeButton);    

      

These layouts will mark the preferred sizes of your buttons

As for opening another window, well, you've already created it, so the process is pretty much the same. Having said that, you might consider taking a look at Using Multiple JFrames: Good or Bad Practice? before letting yourself be deceived.



The best approach might be to use JMenuBar

both JMenuItem

"open" and "exit" actions. Have a look at How to use the menu then you can use CardLayout

to switch between views like

From a pure point of view (I know this is just practice, but perfect practice makes perfect), I won't distribute anything from JFrame

and will instead rely on building your core GUIs around something like JPanel

.

This gives you flexibility in how you use these components, as you can add them to frames, applets, or other components ...

+8


source


If you want your buttons to have their own Look and Feel (L & F), add the following to your program: UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

Instead of opening another, JFrame

you need to use it instead JDialog

, usually with a modality set.

In Java, you can only extend one class, and therefore you should carefully consider whether or not you should extend another class. You might be asking yourself, "Am I really extending the functionality of the JFrame?" If the answer is no, then you really want to use an instance variable.



Below is a sample program from the above guidelines:

JFrame with two buttonsJDialog with modality set

import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

public class MyApplication {
    private JFrame myframe; // instance variable of a JFrame
    private JDialog mydialog;

    public MyApplication() {
        super();
        myframe = new JFrame(); // instantiation
        myframe.setSize(new Dimension(400, 75));
        myframe.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

        JButton btnNewWindow = new JButton("Open New Window");
        btnNewWindow.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                mydialog = new JDialog();
                mydialog.setSize(new Dimension(400,100));
                mydialog.setTitle("I got you! You can't click on your JFrame now!");
                mydialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // prevent user from doing something else
                mydialog.setVisible(true);
            }
        });
        myframe.getContentPane().add(btnNewWindow);

        JButton btnCloseProgram = new JButton("Close Program :(");
        btnCloseProgram.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                myframe.dispose();
            }
        });
        myframe.getContentPane().add(btnCloseProgram);
        myframe.setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | UnsupportedLookAndFeelException e1) {
            e1.printStackTrace();
        }

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new MyApplication();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}

      

+4


source


I'm not sure about your question what you want to do. Do you want to open a new JFrame or do you want to add a JPanel to an existing frame.

To open a new JFrame using a button, instantiate the JFrame in the button's actionPerformed method. In your case, it will look something like this:

    openReportSelection.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            JFrame frame = new JFrame();
            // Do something with the frame
            }
        }
    });

      

+1


source


You probably want to create and open a new JFrame. To do this, you first need to instantiate an object from the JFrame class. As an example, Let the instance be a new JFrame with specific constraints.

JFrame testFrame = new testFrame();
verificationFrame.setBounds(400, 100, 250, 250);

      

Then you need to create your components like JButtons, Jlabels, etc. and then add them to a new testFrame object.

for example create a Jlabel and add its testFrame:

JLabel testLbl = new JLabel("Ok");
testLbl.setBounds(319, 49, 200, 30);
testFrame.getContentPane().add(testLbl);

      

Now, suppose you have a Jbutton called "jbutton" and clicking on it creates a new JFrame and adds a Jlabel to it:

jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JFrame testFrame = new testFrame();
verificationFrame.setBounds(400, 100, 250, 250);
Label testLbl = new  JLabel("Ok");
testLbl.setBounds(319, 49, 200, 30);
testFrame.getContentPane().add(testLbl);
}}});

      

0


source







All Articles