Insert Button in JPanel - java

I am using swing in Java and I need to create a JButton and put it in a JPanel.
I reed tutorials and I did this:
public void crearNuevaMiga(String nombre)
{
JButton nuevo = new JButton(nombre);
this.MigasDePan.add(nuevo);
nuevo.setVisible(true);
nuevo.setLocation(new Point(migaX, migaY));
System.out.println(nuevo.getLocation().x + " "+ nuevo.getLocation().y);
migaX = migaX-avanceMigas;
}
I do that and when I call the function, I cant see the button. I put a button with the designer of NetBeans and get X and Y Location. Then, in the variables migaX and migaY I put that X and Y Location, so the button need to be in the same position, but it is not there.
Anyone knows why? Maybe putting the location in that way is not correct?
Thanks for your time!
EDIT: MigasDePan is my JPanel

Here's a simple example of putting a JButton in a JPanel, and putting the JPanel in a JFrame. I created this code without using any GUI builder.
I called the SwingUtilities invokeLater method in the main method to put the creation and use of the Swing components on the Event Dispatch thread. Oracle and I insist that you start every Swing application on the Event Dispatch thread.
I used a JFrame. You must call the JFrame methods in the order they are called in the run method.
I used a JPanel. I put the JButton in the middle of the JPanel, since it's the only component on the JPanel.
I used a Swing layout, the Border Layout. Different Swing layouts are used to create different Swing component layouts.
Here's the short, self-contained, runnable code.
package com.ggl.testing;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MyButton implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new MyButton());
}
#Override
public void run() {
JFrame frame = new JFrame("My Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JButton myButton = new JButton("My Button");
panel.add(myButton);
return panel;
}
}

By default components have a size of (0, 0) so there is nothing to paint.
When you dynamically add a button to a visible GUI you need to invoke the layout manager so the components size/location can be determined by the layout manager.
The basic code is:
panel.add(...);
panel.revalidate();
panel.repaint();

Related

Troubles with Java Swing

I have the following code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main
{
public static void main(String[] args)
{
Window window = new Window("This is a title", 450, 350);
JButton buttonExit = new Button("Exit", 75, 25);
window.addElement(buttonExit);
window.build();
}
}
class Window // extend the current class
{
public Window window;
public JFrame frame;
public JPanel panel;
public String title;
// instantiate object with the constructor
public Window(String title, int width, int height)
{
this.frame = new JFrame(title);
this.frame.setPreferredSize(new Dimension(width, height));
this.frame.setLocationRelativeTo(null); // centers the main window relative to the center of the screen dimension
this.panel = new JPanel();
this.panel.setPreferredSize(new Dimension(width, height));
//this.panel.setLayout(new FlowLayout());
this.frame.add(panel);
}
public void build()
{
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.pack(); // removes all unnecessary pixel space from the form
this.frame.setVisible(true);
this.frame.setSize(frame.getPreferredSize());
}
public void addElement(JButton element)
{
this.panel.add(element);
}
}
class Button extends JButton // extend the current class
{
public Button(String text, int width, int height)
{
JButton button = new JButton();
button.setPreferredSize(new Dimension(width, height));
button.setText(text);
button.setVisible(true);
new ButtonHandler(button);
}
}
class ButtonHandler implements ActionListener
{
public ButtonHandler(JButton button)
{
button.addActionListener(this);
}
public void actionPerformed(ActionEvent actionEvent) {
System.exit(0);
}
}
I have two problems with this:
The button is compressed and won't show its text
I cannot get the event handler to work and don't appear to get why
As a side note, I know that I don't specify a LayoutManager here, but I had this implemented before and it didn't solve my issue (I tried the FlowLayoutManager and the GridBagLayout [this would be my desired one, due to its flexibility]).
Can someone tell me, what I am doing wrong here? I've only worked with C# and WPF/WinForms before...
Issue 1:
Your custom Button class is-a JButton but also has-a JButton (named button) in the constructor.
The problem here is you install the ButtonHandler class to the button of the constructor, not the custom Button itself (which is referred to as this inside the constructor).
Issue 2:
When you set the [preferred] size of the JFrame property named frame (in the custom class named Window), you are not setting the frame's contents' [preferred] size, but the size of the whole JFrame, which includes the bar located at the top of the frame (which has the title of the frame).
That lets the contents of the frame to have a space less than the preferred size, because the preferred size is set to the whole frame.
I know, you are also setting the preferred size of the JPanel named panel, which is added to the frame, but when you pack the frame, then the preferred size of the frame is prioritized rather than the preferred size of the contents of the frame, so that's probably why you are seeing the button compressed.
Let me demonstrate what I mean, with a bit of code:
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestFramePrefSz {
public static void main(final String[] args) {
SwingUtilities.invokeLater(() -> {
final JFrame frame = new JFrame("Testing JFrame preferred size");
final JPanel contents = new JPanel();
contents.setPreferredSize(new Dimension(200, 200));
frame.setPreferredSize(new Dimension(200, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(contents);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
System.out.println(contents.getSize());
});
}
}
As you can see, the dimension object printed (which is the actual size of the panel) is about 184x161 rather than 200x200 requested, because the preferred size of the frame is also set to 200x200 (which includes the title of the frame etc...).
The solution, is to only set the preferred size of the contents, not the frame (in this particular scenario at least).
So you should:
Remove the line this.frame.setSize(frame.getPreferredSize()); inside the build method.
Remove the line this.frame.setPreferredSize(new Dimension(width, height)); inside the constructor of the custom class named Window.
Issue 3:
The line this.frame.setLocationRelativeTo(null); inside the constructor of the custom class named Window, is not effective in that place.
Imagine that, when you call this method, it has to determine the location of the frame to set it.
So it needs to know first of the size of the screen and then the size of the frame itself.
But what is the size of the frame at the point where you call this method? It is about 0x0. Not the preferred size as you might expect.
That makes the calculation of the frame's location to be such that the frame will not be centered at the screen.
That's because the preferred size is a property of the frame, which is a different property than the size.
So you either have to setSize prior making the call, or better to set the preferred size of the contents of the frame (ie this.panel), then call pack on the frame and finally call the method this.frame.setLocationRelativeTo(null).
Then you are free to set the frame to visible to see where it is located in the screen (ie should be centered).
So the solution is to follow a pattern like the following:
Create the frame, add the contents of the frame to it and set the contents' preferred size.
Call pack on the frame (remember this call will change the size of the frame, according to the preferred sizes of the contents of the frame or the frame's itself).
Call setLocationRelativeTo(null) on the frame.
Call setVisible(true) on the frame.
If you take a look at your code, you are instead doing:
Create the frame.
Set the preferred size of the frame.
Call setLocationRelativeTo(null) on the frame (but the size of the frame is not set yet).
Add the contents of the frame to it (ie the panel).
Call addElement which adds more content to the panel.
Call pack on the frame (remember the preferred size of the frame is set up to this point, so it will override any other preferred sizes, such as the contents' preferred size).
Call setVisible(true) on the frame.
Call setSize on the frame, with the preferred size of it. So you are overwriting the size the frame has had from step 6.
I don't know what you're using as a tutorial. I recommend the Oracle tutorial, Creating a GUI With JFC/Swing. You can skip the Netbeans section, but I recommend going through the rest of the sections.
I created the following GUI.
The Exit button works, disposing of the GUI. The X in the upper right also disposes of the GUI.
Here's the runnable example code. The explanation follows the code.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JButtonExample implements Runnable{
public static void main(String[] args) {
SwingUtilities.invokeLater(new JButtonExample());
}
private JFrame frame;
#Override
public void run() {
frame = new JFrame("This is a title");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
exitProcedure();
}
});
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(300, 200));
panel.setBorder(BorderFactory.createEmptyBorder(
75, 100, 75, 100));
JButton button = new JButton("Exit");
button.addActionListener(new ExitListener(this));
panel.add(button, BorderLayout.CENTER);
return panel;
}
public void exitProcedure() {
frame.setVisible(false);
frame.dispose();
System.exit(0);
}
public class ExitListener implements ActionListener {
private JButtonExample example;
public ExitListener(JButtonExample example) {
this.example = example;
}
#Override
public void actionPerformed(ActionEvent event) {
example.exitProcedure();
}
}
}
I make a call to the SwingUtilities invokeLater method from the main method. This method makes sure that the Swing components are created and executed on the Event Dispatch Thread.
I separate the JFrame code from the JPanel code. This is so I can focus on one part of the GUI at a time.
The JFrame methods have to be called in a specific order. This is the order that I use for most of my Swing applications.
The WindowListener (WindowAdapter) gives my code control over the closing of the JFrame. This will allow the Exit button actionListener to close the JFrame. A WindowListener is not a simple concept.
The JFrame defaultCloseOperation is usually set to EXIT_ON_CLOSE. In order for the WindowListener to work, I had to set the defaultCloseOperation to DO_NOTHING_ON_CLOSE.
I let the JFrame determine its own size by using the pack method.
I set the preferred size of the JPanel.
I created an empty border for the JPanel, so the JButton would expand to fill the rest of the JPanel. That's what happens to the component placed in the center of a BorderLayout.
I created an ExitListener class. Because it's an inner class, I didn't have to create a constructor or pass the JButtonExample instance. I created a constructor so you can see how it's done, and how the actionListener method can execute the exitProcedure method of the JButtonExample class.
I hope this JButton example is helpful. The WindowListener is a bit advanced for a simple example, but you can see how it's done.

Can not display the features using JFrame [duplicate]

I'm fairly new to JFrame and I want to know why my items are not showing up on the window. I know i dont have a ActionHandler but I just want my textfield's to show up on my window. Here's my code:
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class FirstGUI extends JFrame{
public void GUI(){
setTitle("Welcome");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(600,600);
JLabel title = new JLabel();
title.setText("Apple Inc. Member Login Port");
title.setFont(new Font("Arial", Font.PLAIN, 24));
JTextField login = new JTextField("Login",10);
JPasswordField pass = new JPasswordField("Password");
add(title);
add(login);
add(pass);
}
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
}
}
but when i run it i get this:
but when i run it i get this:
You get an empty screen because you add the components to the frame after the frame is visible.
As has already been suggested you need to use an appropriate layout manager. FlowLayout is the easiest to start with.
invoke setVisible(true) AFTER adding the components to the frame.
So the code should be more like:
panel.add(...);
panel.add(...);
add(panel);
pack();
setVisible(true);
I agree to MadProgrammer's suggestions (+1)
Well, lets take a look at your program though
You actually have created a JFrame with components in it. Its working fine as well, but your question of "why are my items not showing up in the JFrame" is not because you did something wrong but because missed out something i.e. revalidate()
Try:
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
a.revalidate();
}
I'm not saying this will give you perfect UI.. what I'm trying to say is this will help you understand the Swing better. Learn about Swing Layout managers and then work on your UI to have better results
revalidate(): This component and all parents above it are marked as needing to be laid out. This means the Layout Manager will try to realign the components. Often used after removing components. It is possible that some really sharp swing people may miss this. I would think that you will only know this if you are actually using Swing.
The default layout manager for JFrame is BorderLayout.
This means that your components are essentially all been added ontop of each other.
Try changing the layout manager to something like FlowLayout (for example)...
Take a look at A Visual Guide to Layout Managers and Using Layout Managers for more details.
Also, avoid setSize where possible, use Window#pack instead
Update
I'd also like to introduce you to Initial Threads which should be used to launch your UI code...
The only one reason :
setVisible(True); method for the frame should be put on the end of the code.
if you give this line on the top of the code that is when you create a frame. This will cause that problem.
Don't add the components directly to your frame. Instead add to the content pane, which is where a JFrame stores all of the components that it draws. Usually this is a JPanel.
Here is an example:
public class GUI
{
private JPanel content;
public void GUI
{
/*Other code*/
content = new JPanel();
add(content); //make content the content pane
content.add(title);
content.add(login);
content.add(pass);
}
If that fails, call setVisible(true) and setEnabled(true) on all of your components.
On a side note you may want to make your GUI function a constructor.
import javax.swing.*;
import java.awt.*;
class Myframec extends JFrame
{
Myframec()
{
Container c = this.getContentPane();
c.setLayout(null);
this.setBounds(10,10,700,500);
this.setTitle("Welcome");
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBounds(0,0,700,500);
panel.setBackground(Color.gray);
panel.setLayout(null);
c.add(panel);
Font f = new Font("Arial",Font.BOLD,25);
Font f1 = new Font("Arial",Font.BOLD,20);
JLabel lable = new JLabel();
lable.setBounds(130,10,400,100);
lable.setText("Apple Inc. Member Login Port");
lable.setFont(f);
panel.add(lable);
JTextField login = new JTextField("Login",10);
login.setBounds(120,150,400,30);
login.setFont(f1);
panel.add(login);
JPasswordField pass =new JPasswordField("Password");
pass.setBounds(120,200,400,30);
pass.setFont(f1);
lable.setFont(f);
panel.add(pass);
c.setVisible(true);
this.setVisible(true);
}
public static void main(String[] argm)
{
Myframec frame = new Myframec();
frame.setVisible(true);
}
}

JFrame Image wont appear, require refresh? [duplicate]

I'm fairly new to JFrame and I want to know why my items are not showing up on the window. I know i dont have a ActionHandler but I just want my textfield's to show up on my window. Here's my code:
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class FirstGUI extends JFrame{
public void GUI(){
setTitle("Welcome");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(600,600);
JLabel title = new JLabel();
title.setText("Apple Inc. Member Login Port");
title.setFont(new Font("Arial", Font.PLAIN, 24));
JTextField login = new JTextField("Login",10);
JPasswordField pass = new JPasswordField("Password");
add(title);
add(login);
add(pass);
}
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
}
}
but when i run it i get this:
but when i run it i get this:
You get an empty screen because you add the components to the frame after the frame is visible.
As has already been suggested you need to use an appropriate layout manager. FlowLayout is the easiest to start with.
invoke setVisible(true) AFTER adding the components to the frame.
So the code should be more like:
panel.add(...);
panel.add(...);
add(panel);
pack();
setVisible(true);
I agree to MadProgrammer's suggestions (+1)
Well, lets take a look at your program though
You actually have created a JFrame with components in it. Its working fine as well, but your question of "why are my items not showing up in the JFrame" is not because you did something wrong but because missed out something i.e. revalidate()
Try:
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
a.revalidate();
}
I'm not saying this will give you perfect UI.. what I'm trying to say is this will help you understand the Swing better. Learn about Swing Layout managers and then work on your UI to have better results
revalidate(): This component and all parents above it are marked as needing to be laid out. This means the Layout Manager will try to realign the components. Often used after removing components. It is possible that some really sharp swing people may miss this. I would think that you will only know this if you are actually using Swing.
The default layout manager for JFrame is BorderLayout.
This means that your components are essentially all been added ontop of each other.
Try changing the layout manager to something like FlowLayout (for example)...
Take a look at A Visual Guide to Layout Managers and Using Layout Managers for more details.
Also, avoid setSize where possible, use Window#pack instead
Update
I'd also like to introduce you to Initial Threads which should be used to launch your UI code...
The only one reason :
setVisible(True); method for the frame should be put on the end of the code.
if you give this line on the top of the code that is when you create a frame. This will cause that problem.
Don't add the components directly to your frame. Instead add to the content pane, which is where a JFrame stores all of the components that it draws. Usually this is a JPanel.
Here is an example:
public class GUI
{
private JPanel content;
public void GUI
{
/*Other code*/
content = new JPanel();
add(content); //make content the content pane
content.add(title);
content.add(login);
content.add(pass);
}
If that fails, call setVisible(true) and setEnabled(true) on all of your components.
On a side note you may want to make your GUI function a constructor.
import javax.swing.*;
import java.awt.*;
class Myframec extends JFrame
{
Myframec()
{
Container c = this.getContentPane();
c.setLayout(null);
this.setBounds(10,10,700,500);
this.setTitle("Welcome");
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBounds(0,0,700,500);
panel.setBackground(Color.gray);
panel.setLayout(null);
c.add(panel);
Font f = new Font("Arial",Font.BOLD,25);
Font f1 = new Font("Arial",Font.BOLD,20);
JLabel lable = new JLabel();
lable.setBounds(130,10,400,100);
lable.setText("Apple Inc. Member Login Port");
lable.setFont(f);
panel.add(lable);
JTextField login = new JTextField("Login",10);
login.setBounds(120,150,400,30);
login.setFont(f1);
panel.add(login);
JPasswordField pass =new JPasswordField("Password");
pass.setBounds(120,200,400,30);
pass.setFont(f1);
lable.setFont(f);
panel.add(pass);
c.setVisible(true);
this.setVisible(true);
}
public static void main(String[] argm)
{
Myframec frame = new Myframec();
frame.setVisible(true);
}
}

New JCheckboxes not appearing below eachother

I am trying to make a basic program where whenever you press a button, a JCheckbox is generated and added below the other JCheckbox on a panel. I figured out how to generate the JCheckbox with a ActionListener but I can't figure out how to get each new check box to appear below the previous one. Everything else seems to be working but I can't get this location thing to work.
box.setVisible(true);
_p.add(box);
int i = 0;
int u = i++;
box.setAlignmentX(0);
box.setAlignmentY(u);
Here is a sample of my code. I've been stuck on this problem for a very long time and would greatly appreciate any and all help.
Check out the Swing tutorial on Using Layout Managers. You could use a vertical BoxLayout or a GridBagLayout or maybe a GridLayout.
Whatever layout you choose to use the basic code for adding components to a visible GUI is:
panel.add(...);
panel.revalidate();
panel.repaint();
The other statements in your code are not necessary:
//box.setVisible(true); // components are visible by default
The following methods do not set a grid position.
//box.setAlignmentX(0);
//box.setAlignmentY(u);
JCheckbox lives in a container like a JPanel (that means that you add checkbox to a panel) . A JPanel have a layoutManager. Take a look about Using Layout Managers
You could use BoxLayout with Y_AXIS orientation or a GridLayout with 1 column and n rows.
Example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CheckBoxTest {
private JPanel panel;
private int counter=0;
public CheckBoxTest(){
panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
JButton button = new JButton(" Add checkbox ");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
panel.add(new JCheckBox("CheckBox"+Integer.toString(counter++)));
//now tell the view to show the new components added
panel.revalidate();
panel.repaint();
//optional sizes the window again to show all the checkbox
SwingUtilities.windowForComponent(panel).pack();
}
});
panel.add(button);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Checkbox example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(Boolean.TRUE);
CheckBoxTest test = new CheckBoxTest();
frame.add(test.panel);
//sizes components
frame.pack();
frame.setVisible(Boolean.TRUE);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Unable to set size and location of button in java

I was just writing an application and i was not able to set location and size of button to desired values. whenever i open code the button comes at same location and with same size
Here is my code
public class main_class {
public static void main(String args[]){
Main_page mp = new Main_page();
mp.start();
}
}
Second file is:
import javax.swing.*;
import java.awt.*;
public class Main_page extends JPanel {
private static final long serialVersionUID = 1L;
public void start(){
JPanel panel1 = new JPanel();
panel1.setBackground(Color.pink);
JButton Button1 = new JButton("Programmer");
Button1.setSize(10, 100);
Button1.setLocation(200,500);
panel1.add(Button1);
JFrame frame1 = new JFrame("Main Window");
frame1.setSize(700,500);
frame1.setContentPane(panel1);
frame1.setResizable(false);
frame1.setVisible(true);
}
}
what is the problem.
What is the problem?
I'm so glad you asked that question. It's not just a matter of getting a Swing application to work. You must get the Swing application to work correctly so that you can add more functionality to your Swing application without your Swing application breaking.
I added a call to SwingUtilities invokeLater in the main method. This call ensures that the Swing components are defined and used on the Event Dispatch thread (EDT).
I changed the name of your class to MainPage to conform to Java standards for naming classes.
I implemented Runnable to make the invokeLater method parameter easier to define.
I removed the extends of JPanel. You use Swing components. The only reason to extend a Swing component is when you want to override one of the component methods. The only reason you extend any Java class is when you want to override one of the class methods.
I changed the name of your MainPage method to run.
I set a layout (FlowLayout) for your JPanel. You must always use a layout manager for your Swing components.
I made button1 lowercase. Java field names are lowercase, so you can easily differentiate them from class names.
I added a call to the JFrame setDefaultCloseOperation to your run method. Without this call, your Swing application will not stop executing when you close the window. After a while, you'll have dozens of copies of your Swing application running, with no easy way to stop them.
I added a call to the JFrame pack to let the JFrame expand or contract to fit the components, rather than be a fixed size.
Here's the revised code. I put the main method in the MainPage class to make it easier to paste the code.
package com.ggl.testing;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainPage implements Runnable {
#Override
public void run() {
JPanel panel1 = new JPanel();
panel1.setBackground(Color.pink);
panel1.setLayout(new FlowLayout());
JButton button1 = new JButton("Programmer");
panel1.add(button1);
JFrame frame1 = new JFrame("Main Window");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.add(panel1);
frame1.pack();
frame1.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new MainPage());
}
}
if you want to set the size and location manually then you can use panel1.setLayout(null); as people have said in the comments this isn't recommended.

Categories

Resources