As practice, I've been trying to make a simple tic tac toe game to see how layouts work in java. Now that I have the base code, with all of the rules and variable checks, I cannot find out how to get the buttons to line up the way I want. I wanted to make a 3x3 grid of buttons, but whenever I try a tutorial online or find someone with a similar problem, it always leads to the buttons not showing up at all. The following code gets the buttons on the screen, but doesn't arrange them.
package game;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame{
//JPanel
JPanel pnlMainBoard = new JPanel();
//Buttons
JButton btnTest = new JButton("Test");
JButton btnAI = new JButton("A1");
JButton btnBI = new JButton("B1");
JButton btnCI = new JButton("C1");
JButton btnAII = new JButton("A2");
JButton btnBII = new JButton("B2");
JButton btnCII = new JButton("C2");
JButton btnAIII = new JButton("A3");
JButton btnBIII = new JButton("B3");
JButton btnCIII = new JButton("C3");
public Main(){
//Layout
//pnlMainBoard.setLayout(null);
//Game set bounds
btnTest.setBounds(60,400,220,30);
//JPanel bounds
pnlMainBoard.setBounds(800,800,200,100);
//Add buttons to frame
pnlMainBoard.add(btnTest);
pnlMainBoard.add(btnAI);
pnlMainBoard.add(btnBI);
pnlMainBoard.add(btnCI);
pnlMainBoard.add(btnAII);
pnlMainBoard.add(btnBII);
pnlMainBoard.add(btnCII);
pnlMainBoard.add(btnAIII);
pnlMainBoard.add(btnBIII);
pnlMainBoard.add(btnCIII);
add(pnlMainBoard);
//JFrame Properties
setSize(400,400);
setTitle("Ultimate Tic Tac Toe");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
So far this is the only code I've created that successfully puts the buttons on the screen, and when I change it the buttons disappear. How do I make it so I can set the location of the buttons where I want them on the window?
For a 3x3 grid check out the swing grid layout that you can set the JPanel to use like this:
GridLayout grid = new GridLayout(3,3);
JPanel.setLayout(grid);
Where jpanel is the name of your jpanel in your program...
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ThreeByThreeWithButtonLayout {
private JComponent ui = null;
ThreeByThreeWithButtonLayout() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
int gap = 10;
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JButton testButton = new JButton("Test");
JPanel buttonConstrain = new JPanel(
new FlowLayout(FlowLayout.CENTER, gap, gap));
buttonConstrain.add(testButton);
ui.add(buttonConstrain, BorderLayout.PAGE_START);
JPanel gridPanel = new JPanel(new GridLayout(0, 3, 5, 5));
gridPanel.setBorder(new EmptyBorder(gap, gap, gap, gap));
ui.add(gridPanel, BorderLayout.CENTER);
String[] buttonRows = {"A", "B", "C"};
for (int ii = 1; ii < 4; ii++) {
for (String buttonRow : buttonRows) {
JButton b = new JButton(buttonRow + ii);
b.setFont(b.getFont().deriveFont(32f));
gridPanel.add(b);
}
}
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ThreeByThreeWithButtonLayout o = new ThreeByThreeWithButtonLayout();
JFrame f = new JFrame("3x3 + Button");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
GridLayout makes some rows and columns to your frame/panel like this :
GridLayout grid = new GridLayout(3,3);
Jpanel.setLayout(grid);
Related
I am making an UI in a minecraft plugin. Everything is working, except I have a JPanel and it doesn't fill the whole JFrame. So what I want is the JPanel fill the entire JFrame even if we re-scale the window.
I use Layout manager (FlowLayout) for the JPanel.
I tried using a Layout manager for the JFrame, well it didn't solved my problem because it didn't resize the JPanel.. I tried setting the size of the JPanel to the JFrame's size, but when it's resized it doesn't scale with it.
So, how can I do this?
My plugin creates a button for every player and when I click the button it kicks the player.
My code (I can't really post less because I don't know where I need to change something):
public static JFrame f;
public static JTextField jtf;
public static JPanel jp;
public static void creategui()
{
System.out.println("GUI created.");
f = new JFrame("Players");
jp = new JPanel();
jp.setLayout(new FlowLayout(FlowLayout.LEFT));
jp.setBackground(Color.GRAY);
jtf = new JTextField("Reason");
jtf.setPreferredSize(new Dimension(200,20));
jtf.setToolTipText("Write the reason here.");
jp.setSize(new Dimension(200,200));
f.setLayout(null);
f.setSize(500,500);
f.setVisible(true);
jp.add(jtf);f.add(jp, BorderLayout.CENTER);
for (final Player p : Bukkit.getOnlinePlayers())
{
System.out.println("Looping.");
final JButton b = new JButton();
b.setName(p.getName());
b.setText(p.getName());
b.setToolTipText("Kick " + b.getText());
b.setBackground(Color.GREEN);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!b.getBackground().equals(Color.RED))
{
Bukkit.getScheduler().runTask(main, new Runnable() {
public void run() {
Bukkit.getPlayer(b.getText()).kickPlayer(jtf.getText());
b.setBackground(Color.RED);
}
});
}
}
});
jp.add(b);
System.out.println("Button added.");
}
f.add(jp, BorderLayout.CENTER);
}
The question should include an mcve reproducing the problem so we can test it.
It could look like this :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Mcve {
private static List<String> players = Arrays.asList(new String[]{"Player A", "Player B"});
public static void main(String[] args) {
creategui();
}
public static void creategui()
{
JPanel jp = new JPanel();
jp.setBackground(Color.GRAY);
JTextField jtf = new JTextField("Reason");
jtf.setPreferredSize(new Dimension(200,20));
jtf.setToolTipText("Write the reason here.");
jp.setSize(new Dimension(200,200));
jp.add(jtf);
for (final String p : players)
{
final JButton b = new JButton();
b.setText(p);
b.setBackground(Color.GREEN);
b.addActionListener(e -> {
if (!b.getBackground().equals(Color.RED))
{
b.setBackground(Color.RED);
}
});
jp.add(b);
}
JFrame f = new JFrame("Players");
f.setLayout(null);
f.setSize(500,500);
f.add(jp, BorderLayout.CENTER);
f.setVisible(true);
}
}
To make the JPanel fill the entire frame simply remove this line :
f.setLayout(null);
and let the default BorderLayout manager do its work.
Here is a modified version with some additional comments:
public class Mcve {
private static List<String> players = Arrays.asList(new String[]{"Player A", "Player B"});
public static void main(String[] args) {
creategui();
}
public static void creategui()
{
JPanel jp = new JPanel();
jp.setBackground(Color.GRAY);
JTextField jtf = new JTextField("Reason");
jtf.setPreferredSize(new Dimension(200,20));
jtf.setToolTipText("Write the reason here.");
jp.setPreferredSize(new Dimension(250,200)); // set preferred size rather than size
jp.add(jtf);
for (final String p : players)
{
final JButton b = new JButton();
b.setText(p);
b.setBackground(Color.GREEN);
b.addActionListener(e -> {
if (!b.getBackground().equals(Color.RED))
{
b.setBackground(Color.RED);
}
});
jp.add(b);
}
JFrame f = new JFrame("Players");
//f.setLayout(null); null layouts are bad practice
//f.setSize(500,500); let layout managers set the sizes
f.add(jp, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
}
A 1x1 grid layout does the job quite nicely.
window = new JFrame();
panel = new JPanel();
window.setLayout(new java.awt.GridLayout(1, 1));
window.add(panel);
Either set the layout manager for jp (the JPanel in the code you posted) to BorderLayout and add jtf (the JTextField in the code you posted) to the CENTER of jp, as in:
f = new JFrame();
jp = new JPanel(new BorderLayout());
jtf = new JTextField(30); // number of columns
jp.add(jtf, BorderLayout.CENTER);
f.add(jp, BorderLayout.CENTER);
or dispense with jp and add jtf directly to f (the JFrame in the code you posted), as in:
f = new JFrame();
jtf = new JTextField(30);
f.add(jtf, BorderLayout.CENTER);
The key is that the CENTER component of BorderLayout expands to fill the available space.
So I fixed it somehow, this is the code:
public static void creategui()
{
System.out.println("GUI created.");
f = new JFrame("Players");
jp = new JPanel();
jp.setBackground(Color.GRAY);
jp.setSize(200,200);
jtf = new JTextField(30);
jtf.setToolTipText("Write the reason here.");
jp.add(jtf);
for (final Player p : Bukkit.getOnlinePlayers())
{
System.out.println("Looping.");
final JButton b = new JButton();
b.setName(p.getName());
b.setText(p.getName());
b.setToolTipText("Kick " + b.getText());
b.setBackground(Color.GREEN);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!b.getBackground().equals(Color.RED))
{
Bukkit.getScheduler().runTask(main, new Runnable() {
public void run() {
getplr(b.getText()).kickPlayer(jtf.getText());
b.setBackground(Color.RED);
}
});
}
}
});
jp.add(b);
System.out.println("Button added.");
}
f.setLayout(new BorderLayout());
f.add(jp, BorderLayout.CENTER);
f.setSize(500,500);
f.pack();
f.setVisible(true);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a java swing project that looks like this:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.Box;
import javax.swing.BoxLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class DiceGameReplaceDice extends JFrame
{
private JFrame gameFrame;
private JPanel mainPanel;
private JPanel centerPanel = new JPanel();
private JButton diceArray[];
private DiceListener diceListener = new DiceListener();
private ButtonListener buttonListener = new ButtonListener();
private Random rand = new Random();
private int NUM_DICE = 2;
private String diceImages[] = {"./src/1.png", "./src/2.png", "./src/3.png",
"./src/4.png", "./src/5.png", "./src/6.png"};
public static void main(String[] args)
{
new DiceGameReplaceDice();
}
public DiceGameReplaceDice()
{
// Initialize the frame that holds the game
gameFrame = new JFrame();
gameFrame.setSize(800, 600);
gameFrame.setLocation(300, 100);
gameFrame.setTitle("Dice Game");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add Panel
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
// Instantiate a ButtonListener
buttonListener = new ButtonListener();
// Add 1 Button and 1 Label to a newly created panel
// Add new panel to West
JButton buttonW1 = new JButton("Add Die");
buttonW1.setName("W1");
buttonW1.addActionListener(buttonListener);
JPanel panelWest = new JPanel();
panelWest.setLayout(new BoxLayout(panelWest,BoxLayout.Y_AXIS ));
panelWest.setBackground(new Color(0, 0, 122)); // set to blue
panelWest.add(Box.createVerticalGlue());
panelWest.add(buttonW1);
panelWest.add(Box.createVerticalGlue());
mainPanel.add(panelWest, BorderLayout.WEST);
// Create and display center panel with dice
displayCenterPanel();
// Add mainPanel to frame and display the frame
gameFrame.add(mainPanel);
gameFrame.setVisible(true);
}
private void displayCenterPanel()
{
centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel,BoxLayout.X_AXIS ));
centerPanel.setBackground(new Color(0, 122, 0)); // set to green
centerPanel.add(Box.createHorizontalGlue());
diceArray = new JButton[NUM_DICE];
// Add 2 Buttons to center panel with images of 2 random dice
for (int i=0; i<NUM_DICE; i++)
{
// Create dice button
int dieNum = rand.nextInt(6)+1;
diceArray[i] = new JButton(new ImageIcon(diceImages[dieNum-1]));
diceArray[i].setName("Dice" + i);
diceArray[i].addActionListener(diceListener);
// Add to center panel
centerPanel.add(diceArray[i]);
centerPanel.add(Box.createHorizontalGlue());
}
mainPanel.add(centerPanel, BorderLayout.CENTER);
// Add mainPanel to frame and display the frame
gameFrame.add(mainPanel);
gameFrame.setVisible(true);
}
// Implement an (inner) class that implements ActionListener
class DiceListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
NUM_DICE -= 1;
displayCenterPanel();
}
}
// Implement an (inner) class that implements ActionListener
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String button = ((JButton)e.getSource()).getName();
System.out.println("Button Pressed: " + button);
if (button.equals("W1"))
NUM_DICE ++;
System.out.println(NUM_DICE);
displayCenterPanel();
}
}
}
When Clicking the "Add Die" button, a die is added to the screen and is correctly formatted. However, when a die is pressed, and the NUM_DICE is decreased, clicking on the die button results in weird overlaps and "ghost buttons". How do you fix this?
The quick fix would be to remove the centerPanel prior to adding the new one. Add the line
mainPanel.remove(centerPanel);
as the first thing you do inside displayCenterPanel.
However, your way of manipulating the layout dynamically leaves a lot to be desired. Instead of creating a new panel each time, just modify the existing one:
public class DiceGame {
private JPanel centerPanel = new JPanel();
private Random rand = new Random();
private int numDice = 2;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new DiceGame());
}
public DiceGame() {
JFrame gameFrame = new JFrame();
gameFrame.setSize(800, 600);
gameFrame.setTitle("Dice Game");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JButton buttonW1 = new JButton("Add Die");
buttonW1.addActionListener(e -> {
numDice++;
updateCenterPanel();
});
JPanel panelWest = new JPanel();
panelWest.setLayout(new BoxLayout(panelWest, BoxLayout.Y_AXIS));
panelWest.setBackground(new Color(0, 0, 122));
panelWest.add(Box.createVerticalGlue());
panelWest.add(buttonW1);
panelWest.add(Box.createVerticalGlue());
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.X_AXIS));
centerPanel.setBackground(new Color(0, 122, 0));
mainPanel.add(panelWest, BorderLayout.WEST);
mainPanel.add(centerPanel);
gameFrame.add(mainPanel);
gameFrame.setVisible(true);
}
private void updateCenterPanel() {
centerPanel.removeAll();
centerPanel.add(Box.createHorizontalGlue());
JButton[] diceArray = new JButton[numDice];
for (int i = 0; i < numDice; i++) {
diceArray[i] = new JButton(Integer.toString(rand.nextInt(6) + 1));
diceArray[i].setName("Dice" + i);
diceArray[i].addActionListener(e -> {
numDice--;
updateCenterPanel();
});
centerPanel.add(diceArray[i]);
centerPanel.add(Box.createHorizontalGlue());
}
centerPanel.revalidate();
centerPanel.repaint();
}
}
Revalidating and repainting is necessary after invalidating the component hierarchy.
Notes:
Don't create fields when local variables will do.
NUM_DICE is not final, so it should be named numDice.
Calling gameFrame.setVisible(true); when it is already visible does nothing.
When you have a working version of whatever it is you are doing, replace setSize(...) on the JFrame with pack and be sure to calculate the size of its children properly.
Its pretty basic UI, but I cannot setup the JCheckBox buttons so that they are placed immediately after one another (vertically) without any spacing. How would I reduce the spacing seen below?
JPanel debugDrawPanel = new JPanel(new GridLayout(0,1));
JPanel eastPanel = new JPanel(new GridLayout(1,0));
JTabbedPane tab = new JTabbedPane();
click = new ClickPanel(this);
setSettings(new Settings());
for (Setting setting: getSettings().getAll()){
JCheckBox checkBox = new JCheckBox(setting.name);
checkBox.setName(setting.name);
checkBox.addItemListener(new CheckBoxItemListener(this));
debugDrawPanel.add(checkBox);
}
tab.addTab("Object Parameters", click);
tab.addTab("Debug Draw", debugDrawPanel);
It appears that the minimum vertical size is being set by the content of another tab. One way to get around that is to put the GridLayout in the PAGE_START of a BorderLayout before putting the panel with border layout into the tabbed pane.
The panel with GridLayout has an orange BG.
The panel with BorderLayout has a yellow BG.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class TopAlignedComponents {
private JComponent ui = null;
TopAlignedComponents() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
JTabbedPane tb = new JTabbedPane();
ui.add(tb);
Image spacer = new BufferedImage(300, 100, BufferedImage.TYPE_INT_RGB);
tb.addTab("Spacer", new JLabel(new ImageIcon(spacer)));
String[] labels = {"Shapes", "Joints", "AABBs"};
JPanel checkPanel = new JPanel(new GridLayout(0, 1, 4, 4));
checkPanel.setBackground(Color.ORANGE);
for (String label : labels) {
checkPanel.add(new JCheckBox(label));
}
JPanel checkConstrain = new JPanel(new BorderLayout());
checkConstrain.setBackground(Color.YELLOW);
checkConstrain.add(checkPanel, BorderLayout.PAGE_START);
tb.addTab("Check", checkConstrain);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
TopAlignedComponents o = new TopAlignedComponents();
JFrame f = new JFrame("Top Aligned Components");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
If i remember correctly, its because of your layout!
GridLayout divides your windowsize into equal parts, so i think you should either unset your windows size and use pack() or you could switch to a different layout.
( I assume your window's size is or minimum-size is set somewhere )
hi i am trying to make java desktop application where i am trying to make jbutton bottom left i did following code i dont know where i am wrong my code is note working
here is my code
import java.awt.*;
import java.awt.event.*;
import javax.imageio.ImageIO;
import javax.swing.*;
new complete code
public class ApplicationCloseExample
{
private JButton[] buttons;
private void displayGUI()
{
final JFrame frame = new JFrame("Application Close Example");
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
for (int i = 5; i < 8; i++) {
buttons[i] = new JButton(Integer.toString(i));
bottomPanel.add(buttons[i]);
}
// JButton button = new JButton("Comment");
// bottomPanel.add(button);
// frame.getContentPane().add(contentPane, BorderLayout.CENTER);
frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ApplicationCloseExample().displayGUI();
}
});
}
}
How can i achieve this
I'm going to assume the null pointer exception is something to do with your buttons array. Check that you have initialised it properly.
private JButton[] buttons = new JButton[8];
I copied your code into a test project and ran it after some modifications:
public static void main(String[] args) {
final JFrame frame = new JFrame("Application Close Example");
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
for (int i = 5; i < 8; i++) {
buttons[i] = new JButton(Integer.toString(i));
bottomPanel.add(buttons[i]);
}
frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
This produced a frame with three buttons aligned to the bottom left of the window.
There is an elegant solution that I'll give you but maybe it serves. Use WindowsBuilder and adds several buttons and then you look like is placing code. So make yourself an idea of the pattern that follows a setLayout with Flow.
I made a small program with two buttons. I label
the buttons one exiting the program and the second importing files.
I actually let them both to exit the program when ever someone pressed on it
the problem is the buttons taking all the window, why?
I tried GridBagConstraints to resize the buttons some how but no luck anyway here's the full class without imports..
public class Window2 extends JFrame{
private static final long serialVersionUID = 1L;
public Window2(){
super ("ALANAZ imagtor");
setSize(600,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel pnl1 = new JPanel(new GridLayout());
JPanel pnl2 = new JPanel();
//button
JButton butn1 = new JButton("EXIT");
JButton butn2 =new JButton("IMPORT");
butn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JOptionPane.showMessageDialog(null, "exiting ... bye...");
System.exit(0);
}
});
butn2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
JOptionPane.showMessageDialog(null, "can't import now exiting");
System.exit(0);
}
});
GridBagConstraints gb1 = new GridBagConstraints();
gb1.insets = new Insets(15,15,15,15);
//Jlabel
JLabel lbl1 = new JLabel("exit or import an image");
pnl1.add(butn1);
pnl1.add(butn2);
pnl2.add(lbl1);
add(pnl2, BorderLayout.SOUTH);
add(pnl1, BorderLayout.CENTER);
}}
You are misusing your layout managers. Your pnl1 JPanel uses GridLayout (without any row or column constants?!), and if you only add one component to it, it will take up the entire JPanel. You seem to have GridBagConstraints in your code, but no GridBagLayout, which is confusing to me.
The solution is to read up on and understand how to use layout managers. Please have a look at the tutorial link: Laying Out Components Within a Container.
Key is to keep remembering that you can nest JPanels within JPanels. For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class Window2 extends JFrame {
private static final long serialVersionUID = 1L;
private static final int PREF_W = 600;
private static final int PREF_H = 400;
public Window2() {
super("ALANAZ imagtor");
setDefaultCloseOperation(EXIT_ON_CLOSE);
int gap = 3;
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, gap, 0));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
JPanel pnl2 = new JPanel();
JButton butn1 = new JButton("EXIT");
JButton butn2 = new JButton("IMPORT");
butn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "exiting ... bye...");
System.exit(0);
}
});
butn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(null, "can't import now exiting");
System.exit(0);
}
});
JLabel lbl1 = new JLabel("exit or import an image");
buttonPanel.add(butn1);
buttonPanel.add(butn2);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(buttonPanel, BorderLayout.SOUTH);
pnl2.add(lbl1);
add(pnl2, BorderLayout.SOUTH);
add(centerPanel, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public static void main(String[] args) {
Window2 win2 = new Window2();
win2.pack();
win2.setLocationRelativeTo(null);
win2.setVisible(true);
}
}
If you initialize your panel with a BorderLayout instead, and add your buttons using EAST, NORTH, WEST, SOUTH, you will have a quick fix - however I do also recommend reading up on layout managers
JPanel pnl1 = new JPanel(new BorderLayout());
pnl1.add(new JButton(), BorderLayout.SOUTH);