How to centre the Buttons in my JFrame? - java

I am trying to make a board game, I have Player 1 label and player 2 label set to the east and west. I am having trouble centre my 3 x 10 buttons. And is there any simpler way of making all 30 buttons at once? Below is my Code:
JPanel panel = new JPanel();
JButton button1 = new JButton();JButton button2 = new JButton();
JButton button3 = new JButton();JButton button4 = new JButton();
JButton button5 = new JButton();JButton button6 = new JButton();
JButton button7 = new JButton();JButton button8 = new JButton();
JButton button9 = new JButton();JButton button10 = new JButton();
JButton button11 = new JButton();JButton button12 = new JButton();
JButton button13 = new JButton();JButton button14 = new JButton();
JButton button15 = new JButton();JButton button16 = new JButton();
JButton button17 = new JButton();JButton button18 = new JButton();
JButton button19 = new JButton();JButton button20 = new JButton();
JButton button21 = new JButton();JButton button22 = new JButton();
JButton button23 = new JButton();JButton button24 = new JButton();
JButton button25 = new JButton();JButton button26 = new JButton();
JButton button27 = new JButton();JButton button28 = new JButton();
JButton button29 = new JButton();JButton button30 = new JButton();
panel.add(button1);panel.add(button2);panel.add(button3);panel.add(button4);
panel.add(button5);panel.add(button6);panel.add(button7);panel.add(button8);
panel.add(button9);panel.add(button10);panel.add(button11);panel.add(button12);
panel.add(button13);panel.add(button14);panel.add(button15);panel.add(button16);
panel.add(button17);panel.add(button18);panel.add(button19);panel.add(button20);
panel.add(button21);panel.add(button22);panel.add(button23);panel.add(button24);
panel.add(button25);panel.add(button26);panel.add(button27);panel.add(button28);
panel.add(button29);panel.add(button30);
frame.add(panel);
Panel p = new Panel();
p.setLayout(new BorderLayout());
p.add(new Button("Throw dice"), BorderLayout.SOUTH);
//p.add(new Button("dice Draw"), BorderLayout.SOUTH);
p.add(new Label("Player 1"), BorderLayout.EAST);
p.add(new Label("Player 2"), BorderLayout.WEST);
frame.add(p);
panel.setLayout(new GridLayout(3,10));
panel.setSize(new Dimension(500, 200));
frame.setSize(new Dimension(600, 300));
}
}

you can make arrays of JButtons and edit them simply by creating a table of JButtons, and use them with a GridLayout cenetred in Borderlayout.CENTER :
JButton [] buttons = new JButton[n];
for(int i=0;i<n;i++){
buttons[i] = new JButton("label "+ i);
buttons[i].set...
buttons[i].set...
gridlayout.add(buttons[i]);
}
borderlayout.add(gridlayout, BorderLayout.CENTER);
panel.setLayout(borderlayout);
hope this helps.

A way to do it is:
panel.setLayout(new GridLayout(3,10));
panel.setSize(new Dimension(500, 200));
//Add this line
panel.setLocation((frame.getWidth()-panel.getWidth())/2, 0); // 0 is just the Y location
frame.setSize(new Dimension(600, 300));
Look into relative layout to manage all your layouts https://stackoverflow.com/a/5346794/643500
Keep in mind that you want all pieces to layout nicely with each other, otherwise issues can be a pain to deal with. Dahmad Boutfounast's solution is one of those nice ones to have.
And definitely use a list\array to manage all those.

Related

How to separate a JTextField from the rest of the GridLayout

I'm trying to make a calculator as a fun project. But as I try to make it look like a... calculator, it just turns out like one big grid, as follows:
I've tried to follow along with whatever I found on the Internet, but that was a big bust.
Can anyone help me out trying to separate the JTextField so it doesn't do this, and it can be in it's own row?
Here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame {
public Main() {
// Row = ->
// Column = ^
Container cp = getContentPane();
cp.setLayout(new GridLayout(3, 0));
JTextField txtCalc = new JTextField("0");
txtCalc.setHorizontalAlignment(SwingConstants.RIGHT);
JButton btn0 = new JButton("0");
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
JButton btn10 = new JButton("10");
cp.add(txtCalc);
cp.add(btn0);
cp.add(btn1);
cp.add(btn2);
cp.add(btn3);
cp.add(btn4);
cp.add(btn5);
cp.add(btn6);
cp.add(btn7);
cp.add(btn8);
cp.add(btn9);
cp.add(btn10);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Calculator");
setSize(600, 600);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(Main::new);
}
}
Edit:
Now I have the answer! This is my fixed code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame {
public Main() {
Container cp = getContentPane();
cp.setLayout(new GridLayout(3, 0));
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel buttonPanel = new JPanel(new GridLayout(3, 0));
setContentPane(border);
JTextField txtCalc = new JTextField("0");
txtCalc.setHorizontalAlignment(SwingConstants.RIGHT);
txtCalc.setEditable(true);
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
JButton btn0 = new JButton("0");
mainPanel.add(buttonPanel, BorderLayout.CENTER);
mainPanel.add(txtCalc, BorderLayout.NORTH);
buttonPanel.add(btn1);
buttonPanel.add(btn2);
buttonPanel.add(btn3);
buttonPanel.add(btn4);
buttonPanel.add(btn5);
buttonPanel.add(btn6);
buttonPanel.add(btn7);
buttonPanel.add(btn8);
buttonPanel.add(btn9);
buttonPanel.add(btn0);
public static void main(String[] args) {
SwingUtilities.invokeLater(Main::new);
}
}
Have your main panel use a BorderLayout. Put the JTextField in the North position. Put your buttons in a panel that uses GridLayout, then add that panel to your main panel in the Center position.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame {
public Main() {
JPanel mainPanel = new JPanel(new BorderLayout());
setContentPane(mainPanel);
JTextField txtCalc = new JTextField("0");
txtCalc.setHorizontalAlignment(SwingConstants.RIGHT);
JPanel buttonPanel = new JPanel(new GridLayout(3, 0));
JButton btn0 = new JButton("0");
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
buttonPanel.add(txtCalc);
buttonPanel.add(btn0);
buttonPanel.add(btn1);
buttonPanel.add(btn2);
buttonPanel.add(btn3);
buttonPanel.add(btn4);
buttonPanel.add(btn5);
buttonPanel.add(btn6);
buttonPanel.add(btn7);
buttonPanel.add(btn8);
buttonPanel.add(btn9);
mainPanel.add(txtCalc, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Calculator");
setSize(600, 600);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(Main::new);
}
}

Add a gridLayout(2,2) in CENTER

I want to create a gridLayout with 4 buttons at the center of my Layout, and a button to PAGE_END,PAGE_START,LINE_END,LINE_START. My code does show the last buttons I told you, but not the grid button ones.
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Hello World!");
frame.setSize(400,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JPanel p = new JPanel(new BorderLayout());
GridLayout grid = new GridLayout(2,2);
p.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JButton bg1 = new JButton("Button 1");
p.add(bg1, c);
JButton bg2 = new JButton("Button 2");
p.add(bg2, c);
JButton bg3 = new JButton("Button 3");
p.add(bg3, c);
JButton bg4 = new JButton("Button 4");
p.add(bg4, c);
frame.setLayout(new BorderLayout());
JButton b1 = new JButton("TOP");
JButton b2 = new JButton("LEFT");
JButton b3 = new JButton("RIGHT");
JButton b4 = new JButton("BOTTOM");
frame.add(b1,BorderLayout.PAGE_START);
frame.add(b2,BorderLayout.LINE_START);
frame.add(b3,BorderLayout.LINE_END);
frame.add(b4,BorderLayout.PAGE_END);
}
}
You have created the panel p, but you haven't added it to your frame.
Add this line in your code:
frame.add(p,BorderLayout.CENTER);
Also, you must use this line, if you want the buttons in a grid:
p.setLayout(grid);
instead of p.setLayout(new GridBagLayout());

BoxLayout Left Alignment

I'm trying to left align the class and neutral buttons so they are in line with the left most card button. For some reason, setAlignmentX only shifts the buttons half way. Here is the code. Is there away to align the buttons?
private String[] listEntries = {"a","a","a","a","a"};
private JButton remove = new JButton("Remove");
private JList list;
private JButton b1 = new JButton("Class");
private JButton b2 = new JButton("Neutral");
private JPanel page = new JPanel(new CardLayout());
private DefaultListModel listModel = new DefaultListModel();
public Main () {
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel,BoxLayout.PAGE_AXIS));
leftPanel.setLayout(new BoxLayout(leftPanel,BoxLayout.PAGE_AXIS));
rightPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
leftPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel title = new JLabel("Deck Constructor", SwingConstants.CENTER);
title.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
//Set up Deck List
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
list.setVisibleRowCount(-1);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(150, 80));
JLabel listTitle = new JLabel("List");
listTitle.setLabelFor(list);
listScroller.setAlignmentX(LEFT_ALIGNMENT);
rightPanel.add(listTitle);
rightPanel.add(listScroller);
rightPanel.add(remove);
//Set up Card Selection
JPanel buttonPanel = new JPanel();
buttonPanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
b1.setActionCommand("Class");
b2.setActionCommand("Neutral");
b1.addActionListener(this);
b2.addActionListener(this);
buttonPanel.add(b1);
buttonPanel.add(b2);
JPanel classCards = new JPanel(new GridLayout(2,3, 10, 10));
JButton card1 = new JButton("Card 1");
card1.addActionListener(this);
card1.setActionCommand("addCard");
JButton card2 = new JButton("Card 2");
JButton card3 = new JButton("Card 3");
JButton card4 = new JButton("Card 4");
JButton card5 = new JButton("Card 5");
JButton card6 = new JButton("Card 6");
classCards.add(card1);
classCards.add(card2);
classCards.add(card3);
classCards.add(card4);
classCards.add(card5);
classCards.add(card6);
JPanel neutral = new JPanel();
neutral.setBackground(Color.BLUE);
page.add(classCards, "Class");
page.add(neutral, "Neutral");
leftPanel.add(buttonPanel);
leftPanel.add(page);
setPreferredSize(new Dimension(640,640/12*9));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(leftPanel,BorderLayout.CENTER);
getContentPane().add(rightPanel,BorderLayout.EAST);
getContentPane().add(title,BorderLayout.NORTH);
pack();
setVisible(true);
}
It is not perfect solution, but you can use for example:
If you want to keep buttons default size:
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING,1,2));
and delete:
buttonPanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
If you want to fill buttonPanel with buttons:
JPanel buttonPanel = new JPanel(new GridLayout(1,2,2,2));
buttonPanel.setBorder(new EmptyBorder(2,1,2,1));
In (FlowLayout.LEADING,1,2) and in EmptyBorder(2,1,2,1))the 1,2 values are added to match buttonPanel and classCard hgap and vgap.

Java GUI Programming close the current Frame

guys I am new to java programming now I have to deal with GUI programming. I have this simple program for admin to create player for now. I have a view class to show the menus, so when user click on create player the interface will be shown.
then within that menu I have a actionListener which goes to another method and show the pop up menu which then show player created successfully. Now the problem is how can I re show the main menu, and not the create player menu.
There will be a few functions for the admin to deal with but now I just have to finish the first function and the rest will be similar. When clicking on the main menu(create player button) it will go to another function(JFrame) to ask for input, again go to another function to getText from the textfield and save it to file
my codes for tpublic void show() {
JFrame frame = new JFrame("Admin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(300,300));
panel1 = new JPanel(new GridLayout(6,1));
text = new JLabel("Admin Main Menu");
text.setFont(new Font("Lucida",Font.PLAIN,24));
//set panel layout (rows,cols,hgap,vgap)
panel1.setLayout(new GridLayout(0,1,10,10));
button1 = new JButton("Create a player");
button2 = new JButton("Delete a player");
button3 = new JButton("Top up Player's Chips");
button4 = new JButton("Reset Player's password");
button5 = new JButton("Change admin's password");
button6 = new JButton("Logout");
mainPanel.add(text);
panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
panel1.add(button4);
panel1.add(button5);
panel1.add(button6);
mainPanel.add(panel1);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
button1.addActionListener(new createPlayerListener());
button1 will got to create player menu
private class createPlayerListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event)
{
JFrame frame1 = new JFrame("Admin");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
text = new JLabel("Create a Player");
text.setFont(new Font("Lucida",Font.PLAIN,24));
mainPanel = new JPanel(new GridLayout(3,1));
mainPanel.setPreferredSize(new Dimension(500,400));
panel1 = new JPanel();
//panel1.setPreferredSize(new Dimension(300,200));
panel1.setLayout(new GridLayout(4,2,10,10));
name = new JLabel("Enter new player name:");
nameTextfield = new JTextField();
pw = new JLabel("Enter new player password:");
pwTextfield = new JTextField();
chip = new JLabel("Enter new player chips:");
chipTextfield = new JTextField();
button1 = new JButton("Create Player");
mainPanel.add(text);
panel1.add(name);
panel1.add(nameTextfield);
panel1.add(pw);
panel1.add(pwTextfield);
panel1.add(chip);
panel1.add(chipTextfield);
mainPanel.add(panel1);
mainPanel.add(button1);
frame1.add(mainPanel);
frame1.pack();
frame1.setVisible(true);
button1.addActionListener(new playerListener());
}
}
private class playerListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event)
{
String name = nameTextfield.getText();
String pw = pwTextfield.getText();
String chip = chipTextfield.getText();
int chips = Integer.parseInt(chip);
//System.out.println(text);
controller.createPlayer(name, pw, chips);
//pop up window player created
JFrame frame2 = new JFrame();
JOptionPane.showMessageDialog(frame2, "Player Created Successfully!");
}
}
Two issues with your code, creating mainPanel twice, you can do so if you define it locally not globally, otherwise change the names to mainPanel1 and mainPanel2, the second issue is you are calling frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); which closes the application once you close frame1. I tried this code and it works, see the changes I made to it,
JPanel mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(300,300));
JPanel panel1 = new JPanel(new GridLayout(6,1));
JLabel text = new JLabel("Admin Main Menu");
text.setFont(new Font("Lucida",Font.PLAIN,24));
//set panel layout (rows,cols,hgap,vgap)
panel1.setLayout(new GridLayout(0,1,10,10));
JButton button1 = new JButton("Create a player");
JButton button2 = new JButton("Delete a player");
JButton button3 = new JButton("Top up Player's Chips");
JButton button4 = new JButton("Reset Player's password");
JButton button5 = new JButton("Change admin's password");
JButton button6 = new JButton("Logout");
mainPanel.add(text);
panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
panel1.add(button4);
panel1.add(button5);
panel1.add(button6);
mainPanel.add(panel1);
add(mainPanel, BorderLayout.CENTER);
button1.addActionListener(new createPlayerListener());
Here is your createPlayerListner modified, the playerListner stays the same,
private class createPlayerListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event)
{
JFrame frame1 = new JFrame("Admin");
JLabel text = new JLabel("Create a Player");
text.setFont(new Font("Lucida",Font.PLAIN,24));
JPanel mainPanel = new JPanel(new GridLayout(3,1));
mainPanel.setPreferredSize(new Dimension(500,400));
JPanel panel1 = new JPanel();
//panel1.setPreferredSize(new Dimension(300,200));
panel1.setLayout(new GridLayout(4,2,10,10));
JLabel name = new JLabel("Enter new player name:");
nameTextfield = new JTextField();
JLabel pw = new JLabel("Enter new player password:");
pwTextfield = new JTextField();
JLabel chip = new JLabel("Enter new player chips:");
chipTextfield = new JTextField();
JButton button1 = new JButton("Create Player");
mainPanel.add(text);
panel1.add(name);
panel1.add(nameTextfield);
panel1.add(pw);
panel1.add(pwTextfield);
panel1.add(chip);
panel1.add(chipTextfield);
mainPanel.add(panel1);
mainPanel.add(button1);
frame1.add(mainPanel);
frame1.pack();
frame1.setVisible(true);
button1.addActionListener(new playerListener());
}
}

Trying to layout JPanels. Java program layout changes every time I run

First time posting so go easy on me.
I am new to Java and am trying to get 3 JPanels to line up on top of each other. The first image is how I want it to look and it does sometimes when I run the program but as you can see by the other images it doesn't line up every time I run it. Sometimes not even showing some of the images/components.
So how can I get three JPanels to line up one after the other vertically?
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class FrameMain {
static final int MY_MINIMUM = 0;
static final int MY_MAXIMUM = 100;
public static void main(String[] args) {
JFrame frame1 = new JFrame("Harvest Frame Test");
frame1.setVisible(true);
frame1.setSize(800,700);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Container Panel
JPanel container = new JPanel();
container.setSize(800,700);
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
frame1.add(container);
//First Panel
JPanel panel1 = new JPanel();
panel1.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
container.add(panel1);
JButton button1 = new JButton("Add Water");
panel1.add(button1);
JButton button2 = new JButton("Add Food");
panel1.add(button2);
JButton button3 = new JButton("Add Medicine");
panel1.add(button3);
ImageIcon image = new ImageIcon("C:/Users/Nick/Documents/EclipseArt/plant.gif");
JLabel imagelabel = new JLabel(image);
panel1.add(imagelabel);
JProgressBar pbar = new JProgressBar();
pbar.setMinimum(MY_MINIMUM);
pbar.setMaximum(MY_MAXIMUM);
// add to JPanel
panel1.add(pbar);
// Second Panel
JPanel panel2 = new JPanel();
panel2.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
container.add(panel2);
JButton button4 = new JButton("Add Water");
panel2.add(button4);
JButton button5 = new JButton("Add Food");
panel2.add(button5);
JButton button6 = new JButton("Add Medicine");
panel2.add(button6);
ImageIcon image1 = new ImageIcon("C:/Users/Nick/Documents/EclipseArt/plant.gif");
JLabel imagelabel1 = new JLabel(image1);
panel2.add(imagelabel1);
JProgressBar pbar1 = new JProgressBar();
pbar1.setMinimum(MY_MINIMUM);
pbar1.setMaximum(MY_MAXIMUM);
// add to JPanel
panel2.add(pbar1);
// Third Panel
JPanel panel3 = new JPanel();
panel3.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
container.add(panel3);
JButton button7 = new JButton("Add Water");
panel3.add(button7);
JButton button8 = new JButton("Add Food");
panel3.add(button8);
JButton button9 = new JButton("Add Medicine");
panel3.add(button9);
ImageIcon image2 = new ImageIcon("C:/Users/Nick/Documents/EclipseArt/plant.gif");
JLabel imagelabel2 = new JLabel(image2);
panel3.add(imagelabel2);
JProgressBar pbar2 = new JProgressBar();
pbar2.setMinimum(MY_MINIMUM);
pbar2.setMaximum(MY_MAXIMUM);
// add to JPanel
panel3.add(pbar2);
}
//static class Action implements ActionListener {
//public void actionPerformed (ActionEvent e){
//}
//}
}
Move the frame1.setVisible(true); all the way to the bottom. Changing Components on a frame that is already visible can cause issues.

Categories