Ok so im new to programming GUIs in Java and I need some help on how to add buttons and Labels. I went around looking at an example and I figured it this was how it worked to basically add a button:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GUI_Tests extends JFrame{
public static void main(String[] args){
private JButton button;
button = new JButton("pls work");
add(button);
}
}
Well that didnt work at all... Can someone show me how its done and give me some pointers?
You should note that a JFrame has a default BorderLayout which, if not specified, will add a component to a BorderLayout.CENTER position.
When adding components to JFrame, if a different Layout is not specified, then you want to set a component's position, like add(button, BorderLayout.SOUTH);
Also you should use a constructor. Something like this
public class GUI_Tests extends JFrame {
public GUI_Tests(){
JButton button = new JButton("Pls work");
JLabel label = new JLabel("Pls work");
add(button, BorderLayout.CENTER);
add(label, BorderLayout.SOUTH);
}
}
Also you need to remember to set the frame visible.
A simple running program would be something like this
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class GUI_Tests extends JFrame {
public GUI_Tests() {
JButton button = new JButton("Pls work");
JLabel label = new JLabel("Pls work");
add(button, BorderLayout.CENTER);
add(label, BorderLayout.WEST);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new GUI_Tests();
}
});
}
}
The main method may look somewhat crazy to you, but all it is doing is causing the program to run on the Event Dispatch Thread (EDT). I won't go into this too much as you are still a beginner.
What is going on in the run is that all I do is create an instance of me program, which extends JFrame. If I didn't extend JFrame, I would have to explicitly create a JFrame to run the program. All GUI programs need some top-level container to run.
Also you can see in the constructor, that when I added the button and label I set a layout position
add(button, BorderLayout.CENTER);
add(label, BorderLayout.SOUTH);
as I stated earlier, when using a JFrame without specifying a different layout, you should use position with the default `BorderLayout. Other possible positions are
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.CENTER
BorderLayout.NORTH
BorderLayout.SOUTH
Take a look at [Laying Out Components Within a Container]Laying Out Components Within a Container)
Also, noticed I used pack(). What this does is make the frame the perfect with for the preferrsed sizes of the components. It is preferred to pack() rather then setSize() of a frame.
setDefaultCloseOperation(EXIT_ON_CLOSE); makes it so that when x out the frame, the program shuts down.
setLocationRelativeTo(null); set the frame's location in the center of the screen
setVisible(true); makes the frame visible. This should always be called to make the frame visible on start of the program.
Please have a look at the Swing tutorials
You are supposed to add your JButton to a JFrame, but it seems to me that you haven't even created a JFrame yet. You should first create an instance of GUI_Tests, then use the JFrame#add method with your JButton. For example:
public class GUI_Tests extends JFrame {
public GUI_Tests() {
super("My first Swing frame!");
this.setPreferredSize(new Dimension(640, 480));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create your GUI here
this.add(new JButton("Click on me :)"));
this.setVisible(true);
}
}
Actually, I wouldn't be mean to you, but I think you tried to go too fast: in my opinion, you should start by following some tutorial on how to deal with Swing :)
public class GUI_Tests extends JFrame {
private JButton button;
public GUI_Tests() {
setTitle("Title");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // so that the application properly closes when you click close
button = new JButton("pls work");
add(button);
pack(); // resize the frame to its contents
setLocationRelativeTo(null); // center the frame on the screen
}
public static void main(String args[]) {
// properly start a swing application
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI_Tests gui = new GUI_Tests();
gui.setVisible(true); // set the frame visible
}
});
}
}
hope this helps you understand it a bit more. i didn't use any layouts in this code as its just a simple example, however, i highly recommend you to read on built-in layouts in swing and how to use them.
Here's one good start
You need to add your button to a JFrame The basic flow should look something like this:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class GUITests extends JFrame{
public GUITests() {
setTitle("Simple example");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton button = new JButton("pls work");
add(button);
pack();
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUITests ex = new GUITests();
ex.setVisible(true);
}
});
}
}
The GUITests class extends the JFrame class so you can call all the methods that are visible on the JFrame class. In the main method It's just some boiler plate code that calls your constructor for you so that you can see your basic example.
Check out the tutorials here: http://zetcode.com/tutorials/javaswingtutorial/firstprograms/
type
setVisible( true );
setSize( 500 , 500 );
and I think you'll see something. Also get rid of private in the statement private JButton button But you should really put your code in the constructor of the GUI_Tests:
import javax.swing.*;
public class GUI_Tests extends JFrame {
public GUI_Tests() {
JButton button = new JButton( "Hello World" );
add( button );
setVisible( true );
setSize( 500 , 500 );
}
final public static void main( String[] args ) {
GUI_Tests tests = new GUI_Tests();
}
}
Check out the Java tutorial for more help, possibly here: http://docs.oracle.com/javase/tutorial/uiswing/start/index.html
Related
Following is the code in which the jbutton is not showing on the frame. I have also set visible to true. Even then the button doesn't appear.
class gui{
public static void main(String args[]){
layoutBorder lb=new layoutBorder("check");
}
}
class layoutBorder extends JFrame{
layoutBorder(String title){
super(title);
setLayout(null);
setSize(200, 200);
JButton jb=new JButton("JB");
add(jb);
setVisible(true);
}
}
Don't use a null layout!!!
Swing was designed to be used with layout managers.
Read the section from the Swing tutorial o Layout Managers for more information.
I suggest you download the working examples and play with them. The example will also show you how to better structure your code. Maybe start with the code from How to Use Buttons, which has a simple example that adds 3 buttons to a panel and then the panel to the frame.
Also, class names should start with an upper case character. Have you even seen a class in the API that doesn't??? Learn Java conventions and follow them.
camickr is right. Also, always use the AWT event dispatching thread when an application thread needs to update the GUI.
import javax.swing.*;
import java.awt.*;
import java.lang.*;
public class Gui {
public static void main(String args[]) {
SwingUtilities.invokeLater(() -> {
MyFrame frame = new MyFrame("check");
});
}
}
class MyFrame extends JFrame {
MyFrame(String title){
super(title);
setLayout(new BorderLayout());
setSize(200, 200);
JButton jb = new JButton("JB");
add(jb);
setVisible(true);
}
}
If you want null layouts then you need to set sizes and position by yourself. Using the setLocation and setSize methods.
class gui{
public static void main(String args[]){
layoutBorder lb=new layoutBorder("check");
}
}
class layoutBorder extends JFrame{
layoutBorder(String title){
super(title);
setLayout(null);
setSize(200, 200);
JButton jb=new JButton("JB");
jb.setLocation(10, 10);
jb.setSize(40, 30);
add(jb);
setVisible(true);
}
}
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!
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);
}
}
//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);
}
}
I'm trying to add the ScrollPane to my TextArea, but it doesn't appear.
Here's the code:
import javax.swing.*;
public class PracownikGui extends JFrame {
private JPanel Panelek;
private JTextArea Tekscik;
private JScrollPane Skrol;
public PracownikGui() {
setMinimumSize(new Dimension(600, 600));
setLocationRelativeTo(null);
setContentPane(Panelek);
setResizable(false);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
Tekscik();
public void Tekscik() {
Tekscik = new JTextArea(2, 10);
Skrol = new JScrollPane( Tekscik );
Tekscik.setSize(300, 300);
Tekscik.setLocation(20, 70);
Tekscik.setEditable(true);
Tekscik.setLineWrap(true);
add(Tekscik);
}}
Any help, please.
You're shooting yourself in the foot by setting a JTextArea's size or preferredSize since this prevents it from expanding into the JScrollPane:
Tekscik.setSize(300, 300);
set its rows and columns only.
Also you need to add the JScrollPane to the GUI, not the JTextArea.
Also, while null layouts and setBounds() or setSize(...) and setLocation(...) might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
e.g.,
import javax.swing.*;
public class PracownikPanel extends JPanel {
private JTextArea tekscik = new JTextArea(5, 25);
public PracownikPanel() {
tekscik.setLineWrap(true);
tekscik.setWrapStyleWord(true);
JScrollPane skrol = new JScrollPane(tekscik);
skrol.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(skrol);
}
private static void createAndShowGui() {
PracownikPanel mainPanel = new PracownikPanel();
JFrame frame = new JFrame("PracownikPanel");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I made quite a few changes to your code. Your code wouldn't run.
Here's the GUI I created.
As you can see, there's a vertical scroll bar. The default action for the scroll bar is that it doesn't appear until you've filled the JTextArea with text.
Here are the important changes I made to your code.
Class names start with a capital letter. Method names and variable names start with a lower case letter.
A Swing application must start with a call to the SwingUtilities invokeLater method. This ensures that the Swing components are created and used on the Event Dispatch thread (EDT). Since the invokeLater method requires a Runnable, I had the PracownikGui class implement Runnable.
You use Swing components. You don't extend Swing components, or any other Java class, unless you want to override one of the methods in that class.
I removed all of the sizing and positioning statements, except for the statement that defines the rows and columns of the JTextArea. Hovercraft Full Of Eels explained this, but you use Swing layouts to get the arrangement of Swing components you want. The default layout for a JPanel is the FlowLayout. The default layout for a JFrame is the BorderLayout.
I added the JScrollPane to the JPanel. I added the JPanel to the JFrame.
Here's the code.
package com.ggl.testing;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class PracownikGui implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new PracownikGui());
}
private JFrame frame;
private JPanel panelek;
private JTextArea tekscik;
private JScrollPane skrol;
#Override
public void run() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panelek = new JPanel();
tekscik(panelek);
frame.setContentPane(panelek);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public void tekscik(JPanel panelek) {
tekscik = new JTextArea(2, 20);
tekscik.setEditable(true);
tekscik.setLineWrap(true);
skrol = new JScrollPane(tekscik);
panelek.add(skrol);
}
}
I know this is something very simple, but as a complete Java newbie I'm missing it and someone pointing it out would be infinitely helpful. I've stared at the screen and moved things around and still nothing.
Screenshot:
http://i.imgur.com/dwH60.png
This is all that comes up when this is run.
fullGUI.java:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class fullGUI extends JFrame
{
JFrame frame = new JFrame(); //creates frame
public fullGUI() // constructor
{
//setLayout(new BorderLayout());
//add(new shipGrid(), BorderLayout.NORTH);
//add(new shipGrid(), BorderLayout.NORTH);
add(new JRadioButton("Horizontal"), BorderLayout.WEST);
add(new JRadioButton("Vertical"), BorderLayout.WEST);
add(new JTextArea("Instructions to player will go here"), BorderLayout.CENTER);
frame.setSize(400,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Battleship!");
frame.pack(); //sets appropriate size for frame
frame.setVisible(true);
}
}
...called by...
test.java
public class test
{
public static void main(String[] args)
{
new fullGUI();
}
}
name classes in Java from a capital letter
FullGUI already extends JFrame, so no need to create another JFrame inside it
call getContentPane.add() to add to JFrame
use SwingUtilities.invokeLater
So overall something like this
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class FullGUI extends JFrame
{
public FullGUI() // constructor
{
getContentPane().add(new JRadioButton("Horizontal"), BorderLayout.WEST);
getContentPane().add(new JRadioButton("Vertical"), BorderLayout.WEST);
getContentPane().add(new JTextArea("Instructions to player will go here"), BorderLayout.CENTER);
setSize(400,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Battleship!");
pack(); //sets appropriate size for frame
setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new FillGU();
}
});
}
Problem is that you are extending JFrame in your class and creating new object "frame". You're adding components such as JRadioButton or JTextArea into fullGUI and other settings of the JFrame are applicable to frame object. It's up to you which approach you're going to choose, but pick one of them. You can extend JFrame and your class will be a child of JFrame which means you can call all public or protected methods from parent class, no need to create new instance of JFrame. Other way is to not extend JFrame and you have to create new JFrame object instead.
frame.pack() is causing your JFrame to resize according to its contents.
If you have frame.setSize(400,600), even if you don't add anything to its content pane,
the frame will be displayed with size 400x600.
But when you call frame.pack(), the frame will resize. In your case, your frame's content pane does not contain anything. Therefore the pack() method resizes it to only your title bar.
As Nikolay Kuznetsov said in earlier answer, you have extended Jframe in fullGUI so no need to create new Jframe in that class, because every instance of FullGUI will be a new frame.
With you code what happened is that you have created a Frame, say frame1 and instance of fullGUI(In main Method) say frame2, these are two different frames. In the Constructor you have added those controls to the frame2 (add()==this.add()) and said frame1.setvisible(true);
Adding controls to one frame and displaying altogether different frame is the reason why you were unable to see anything on output scree though you would have maximized the screen.
I'm trying to write custom JFrame and JPanel for my Java application. Currently, I just want to have a JPanel with a start button in the very middle of the screen. So, here's the code I have:
package gui;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class SubitizingFrame extends JFrame implements KeyListener {
public SubitizingFrame() {
super("Subitizing");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
add(new LaunchPanel());
pack();
setVisible(true);
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_F5)
System.out.println("F5 pressed");
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
and here is my panel:
package gui;
import instructions.Settings;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class LaunchPanel extends JPanel implements ActionListener {
private JButton startButton;
public LaunchPanel() {
int width = Settings.getScreenSizeX(), height = Settings.getScreenSizeY();
setPreferredSize(new Dimension(width, height));
setLayout(null);
startButton = new JButton("Start");
startButton.setLocation((width/2) - (startButton.getWidth()/2), (height/2) - (startButton.getHeight()/2));
add(startButton);
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
But when the application launches, I don't see anything. Just a big gray screen.
Do not use a null layout. If you simply use the default layout manager of JPanel (i.e. FlowLayout), the JButton with "automagically" be placed in the center. Also, in order to place the JFrame in the middle of the screen, invoke setLocationRelativeTo(null).
Since it's hard to tell what you mean by "screen", this example shows how you center a JButton in a JPanel in a JFrame, that is then centered on the monitor.
public final class CenterComponentsDemo {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame("Center Components Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ButtonPane());
frame.setSize(new Dimension(300, 100)); // Done for demo
//frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class ButtonPane extends JPanel{
public ButtonPane(){
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBackground(Color.PINK);
final JButton button = new JButton("Start");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
add(Box.createVerticalGlue());
add(button);
add(Box.createVerticalGlue());
}
}
}
Recommendations:
Avoid using null layout as this makes your app difficult to upgrade and maintain and makes it potentially very ugly or even non-usable on boxes with different OS's or screen resolutions.
If you have your JPanel use a GridBagLayout and add a single component to it without using GridBagConstraints, it will be placed in the center of the JPanel.
You almost never have to or should extend JFrame and only infrequently need to extend JPanel. Usually it's better to enhance your GUI classes through composition rather than inheritance.
Avoid having your "view" or gui classes implement your listener interfaces. This is OK for "toy" programs, but as soon as your application gains any appreciable size or complexity, this gets hard to maintain.
If you don't use any LayoutManager (which btw you probably should), then you'll need to set the size of the panel as well (along with its position).
Although we strongly recommend that you use layout managers, you can perform layout without them. By setting a container's layout property to null, you make the container use no layout manager. With this strategy, called absolute positioning, you must specify the size and position of every component within that container. One drawback of absolute positioning is that it does not adjust well when the top-level container is resized. It also does not adjust well to differences between users and systems, such as different font sizes and locales.
From: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class LaunchPanel extends JPanel {
private JButton startButton;
public LaunchPanel() {
int width = 200, height = 100;
setPreferredSize(new Dimension(width, height));
setLayout(new GridBagLayout());
startButton = new JButton("Start");
add(startButton);
setBorder( new LineBorder(Color.RED, 2));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, new LaunchPanel());
}
});
}
}
addKeyListener(this);
Don't use KeyListeners. Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings for more information.
The tutorial also has a section on Using Layout Manager which you should read. You should not create GUI's with a null layout.