2

I am trying to build a little program that has a main GUI with 2 buttons. One button closes the program, the other I want to open a new JPanel that will have text fields etc.

I would like to be able to make the buttons so they look like normal application buttons I guess, nice and square, equal size etc. etc., I am not sure how to do this though.

Also, I am unsure how to open a new JFrame from a button click.

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 would be the way to go rather than a JFrame. What would be the best way to do this from a Jbutton click?

Wall-E
  • 43
  • 7
Splunk
  • 311
  • 3
  • 6
  • 20
  • Use [combinations of layout managers](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). – Andrew Thompson Jun 03 '14 at 07:21
  • Do you mean that you want to open a new ```JPanel``` in the given ```JFrame```? – David Yee Jun 03 '14 at 08:04

4 Answers4

10

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 honour the preferred sizes of your buttons

As for opening another window, well, you've already create one, so the process is pretty much the same. Having said that, you might consider having a look at The Use of Multiple JFrames: Good or Bad Practice? before you commit yourself to far.

A better approach might be to use a JMenuBar and JMenuItems to act as the "open" and "exit" actions. Take a look at How to Use Menus then you could use a CardLayout to switch between views instead, for example

From a pure design perspective (I know it's only practice, but perfect practice makes perfect), I wouldn't extend anything from JFrame and instead would rely on building your main GUIs around something like JPanel instead.

This affords you the flexibility to decide how to use these components, as you could add them to frames, applets or other components...

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
4

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

Instead of opening another JFrame, you'll want to instead use a JDialog, typically with modality set.

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

Below is an example program from the above recommendations:

JFrame with two buttons JDialog 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();
                }
            }
        });
    }

}
David Yee
  • 3,515
  • 25
  • 45
1

I am not sure from your question what do wou want to do. Do you want to open a new JFrame or do you want to add a JPanel to the existing frame.

To open a new JFrame using a button, create an instance of the JFrame in the actionPerformed method of the button. In your case it would look similar to this:

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

You're probably looking up to create and open a new JFrame. For this purpose, first you need to instantiate an object from JFrame Class. As an example, Let's instantiate a new JFrame with specific boundries.

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

Then you need to create your components like JButtons, Jlabels and so on, and next you should add them to your new testFrame object.

for example, let's create a Jlabel and add it testFrame:

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

Now let's suppose you have a Jbutton which is named "jbutton" and by clicking it, a new JFrame object will be created and the Jlabel component will be added 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);
}}});
Wall-E
  • 43
  • 7