0

I'm a complete beginner to Java, and I'm finding some answers a bit too technical for me (even the most basic tutorials seem to give me syntax errors when I run the code). How, in really simple terms do I add a JButton to a JFrame? I've got as far as:

import javax.swing.JButton;
import javax.swing.JFrame;

public class JF {

    public static void main(String[] args) {
        JFrame myFrame = new JFrame();
        /*some pretty basic code to initialize the JFrame i.e.
        myFrame.setSize(300, 200);
        This is as far as I got
        */
    }

}

I would seriously appreciate some help!

nick zoum
  • 7,216
  • 7
  • 36
  • 80
Jaems
  • 29
  • 1
  • 2
  • 8
    Go back to the tutorials. If you're getting some error you can't understand, come and ask about that. Don't ask us to write a custom tutorial for you. – khelwood Nov 04 '16 at 10:46
  • 1
    `myFrame.setSize(300, 200);` You've already gone wrong in the second line of code. The way to set the size of a frame is to add all components (with appropriate white space in layout padding and borders) then pack the frame. *"I would seriously appreciate some help!!"* You should go through the [official tutorial](https://docs.oracle.com/javase/tutorial/uiswing/) and ask specific questions if and when they arise. – Andrew Thompson Nov 04 '16 at 10:50
  • *"You've already gone wrong in the second line of code."* Correction, all GUI creation should be done on the Event Dispatch Thread, so even the first line of code is wrong. – Andrew Thompson Nov 04 '16 at 10:52
  • As a second, minor recommendation. Don't use abbreviations like plz or symbols like <3. They are not going to make anyone more likely to help you and in fact turn some people off. Simply write out your problem. The please and thanks are assumed by everyone on here – Lexi Nov 04 '16 at 11:13

2 Answers2

4

Creating a new JFrame

The way to create a new instance of a JFrame is pretty simple. All you have to do is:

JFrame myFrame = new JFrame("Frame Title");

But now the Window is hidden, to see the Window you must use the setVisible(boolean flag) method. Like this:

myFrame.setVisible(true);

Adding Components

There are many ways to add a Component to a JFrame.

The simplest way is:

myFrame.getContentPane().add(new JButton());//in this case we are adding a Button

This will just add a new Component that will fill the JFrame().

If you do not want the Component to fill the screen then you should either make the ContentPane of the JFrame a new custom Container

myFrame.getContentPane() = new JPanel();

OR add a custom Container to the ContentPane and add everything else there.

JPanel mainPanel = new JPanel();
myFrame.getContentPane().add(mainPanel);

If you do not want to write the myFrame.getContentPane() every time then you could just keep an instance of the ContentPane.

JPanel pane = myFrame.getContentPane();

Basic Properties

The most basic properties of the JFrame are:

  • Size
  • Location
  • CloseOperation

You can either set the Size by using:

myFrame.setSize(new Dimension(300, 200));//in pixels

Or packing the JFrame after adding all the components (Better practice).

myFrame.pack();

You can set the Location by using:

myFrame.setLocation(new Point(100, 100));// starting from top left corner

Finally you can set the CloseOperation (what happens when X is pressed) by

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

There are 4 different actions that you can choose from:

  • DO_NOTHING_ON_CLOSE //Nothing happens
  • HIDE_ON_CLOSE //setVisible(false)
  • DISPOSE_ON_CLOSE //Closes JFrame, Application still runs
  • EXIT_ON_CLOSE //Closes Application

Using Event Dispatch Thread

You should initialize all GUI in Event Dispatch Thread, you can do this by simply doing:

class GUI implements Runnable {

    public static void main(String[] args) {
        EventQueue.invokeLater(new GUI());
    }

    @Override
    public void run() {
        JFrame myFrame = new JFrame("Frame Title");

        myFrame.setLocation(new Point(100, 100));
        myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        myFrame.getContentPane().add(mainPanel);
        mainPanel.add(new JButton("Button Text"), BorderLayout.CENTER);

        myFrame.pack();
        myFrame.setLocationByPlatform(true);
        myFrame.setVisible(true);
    }

}
nick zoum
  • 7,216
  • 7
  • 36
  • 80
  • It seems SO only notifies us when we've actually contributed a comment on the specific question or answer. *"Does this answer, now need any improvement?"* Only two slight areas of improvement. 1) `myFrame.setSize(new Dimension(300, 200));` will become redundant when `myFrame.pack();` is called. The latter method call will not only call for the components to be laid out, but will also reduce the frame to the size it needs to be in order to display the components it contains (and the icons of the title bar). 2) (Personal bug-bear of mine) .. – Andrew Thompson Nov 04 '16 at 15:08
  • @AndrewThompson Had both `setSize()` and `setLocation()`, but accidentally removed the second one instead of the first, fixed it now. – nick zoum Nov 04 '16 at 15:10
  • .. `myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);` would best be `myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);`. It rarely makes a difference, except when there are other non-daemon threads running, or other top-level containers open. If the VM does not end itself automatically on closing the main frame, best to investigate exactly why. 3) Not mentioned in the code but nice for the user is to call `myFrame.setLocationByPlatform(true);` before setting the GUI visible. This will locate the GUI wherever the OS would naturally have put the 'next app. opened. .. – Andrew Thompson Nov 04 '16 at 15:12
  • .. e.g. as seen in [this answer](http://stackoverflow.com/a/7143398/418556) – Andrew Thompson Nov 04 '16 at 15:12
  • Now, after those points, I'll list some things that are good about the code. 1) Uses an instance of a frame, rather than extending frame. 2) Creates the GUI on the EDT. 3) Calls `pack()` and uses layouts to suggest a minimum size. 4) Passes the button text in the constructor, making the code shorter. :) – Andrew Thompson Nov 04 '16 at 15:15
  • Oh, but just spotted another concern.. The default layout of a panel is `FlowLayout`, yet the button is added using the constraint of a `BorderLayout`. Either explicitly set the layout of the panel, or drop the constraint. - Even given those 'concerns', this is the most 'solid coding' that has yet appeared for this question. – Andrew Thompson Nov 04 '16 at 15:17
  • @AndrewThompson **1)** Why would `extends JFrame` be bad? **2)** I've always been programming in Windows, I've never seen a difference when using `setLocationByPlatform(true)`. Is the behavior different for other OS? **3)** Followed your instructions and fixed my answer. – nick zoum Nov 04 '16 at 15:30
  • Thanks, really helpful! – Jaems Nov 04 '16 at 15:34
  • 1
    1) Extending is bad whenever it is not needed. Think of it this way. When using a `JButton`, a `JPanel` or a `JMenuItem`, would you extend the class or simply use an instance? I'd almost always just use an instance. The only exception would be `JPanel`, when doing custom painting, where we actually *change* the behaviour of on or more methods (in that case, the `patinComponent(Graphics)` method). Prefer composition (use instance of) over inheritance (extends). 2) *"Is the behavior different for other OS? "* The answer I linked shows screenshots of the behaviour on different OS'. – Andrew Thompson Nov 04 '16 at 15:40
  • @AndrewThompson 1) in the case of creating a new custom `JButton` that also has an image as a background that is used in multiple cases wouldn't it be better to extend the `JButton class`? 2) Ok got it, I very rarely use more than two `JFrames` simultaneously and I never use the same `JFrame` more than once (except from debugging), so I never noticed. – nick zoum Nov 04 '16 at 15:47
  • *"`JButton` that also has an image as a background"* Yes, that's a case where you'd extend button, but if the button requires no text, I'd just set the image as the icon and remove the space from around it, as seen in [this answer](http://stackoverflow.com/a/10862262/418556) - which uses a combination of buttons and labels to display different parts of a single image. Truth is, I've *never* needed to use a button that has a BG image. If doing so, you would also need to make sure the button text does not become obscured by parts of the image that are the same color as the text. – Andrew Thompson Nov 04 '16 at 15:58
  • @Jaems If you like this answer then you can [accept it by following this step (click on link)](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). You could also upvote it. – nick zoum Nov 08 '16 at 16:34
0
//I hope this will help

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
public class JF extends JFrame
{
    private JButton myButton;//Here you begin by declaring the button
    public JF()//Here you create you constructor. Constructors are used for initializing variable
    {
        myButton = new JButton();//We initialize our variable
        myButton.setText("My Button"); //And give it a name
        JPanel panel1 = new JPanel();//In java panels are useful for holding content
        panel1.add(myButton);//Here you put your button in the panel

        add(panel1);//This make the panel visible together with its contents

        setSize(300,400);//Set the size of your window
        setVisible(true);//Make your window visible
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args)
    {
        JFrame frame = new JF();
        frame.setTitle("My First Button");
        frame.setLocation(400,200);
    }
}
Mikehenry
  • 11
  • 1