import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
@SuppressWarnings("serial")
public class ButtonLocationDemo extends JFrame implements ActionListener{
/// Create variables
private JButton button;
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
// private BufferedImage image;
public ButtonLocationDemo(){
// button1.setForeground(Color.WHITE);
// Add buttons
JPanel p = new JPanel();
button = new JButton("Doorgaan");
button1 = new JButton("Opslaan");
button2 = new JButton("Spelregels");
button3 = new JButton("Naar hoofdmenu");
button4 = new JButton("Afsluiten");
button1.setAlignmentX(Component.CENTER_ALIGNMENT);
button1.setBackground(Color.black);
button1.setForeground(Color.white);
button1.setBorder(null);
button1.setBounds(250,150,100,50);
button.setBounds(250,50,100,50);
button.setBackground(Color.black);
button.setForeground(Color.white);
button.setBorder(null);
button2.setBounds(250,250,100,50);
button2.setBackground(Color.black);
button2.setForeground(Color.white);
button2.setBorder(null);
button3.setBounds(250,350,150,50);
button3.setBackground(Color.black);
button3.setForeground(Color.white);
button3.setBorder(null);
button4.setBounds(250,450,100,50);
button4.setBackground(Color.black);
button4.setForeground(Color.white);
button4.setBorder(null);
// Add buttons
p.add(button);
p.add(button1);
p.add(button2);
p.add(button3);
p.add(button4);
p.setBackground(Color.black);
p.setLayout(null);
getContentPane().add(p);
//setLayout(null);
setDefaultCloseOperation(3);
setSize(720,720);
setVisible(true);
// Add actionListeners
button.addActionListener(this);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
}
public static void main(String[] args) {
new ButtonLocationDemo();
}
// Action performer
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==this.button){
System.out.println("Doorgaan");
}
if (e.getSource()==this.button1){
System.out.println("Opslaan");
}
if (e.getSource()==this.button2){
System.out.println("Spelregels");
}
if (e.getSource()==this.button3){
System.out.println("Naar hoofdmenu");
}
if (e.getSource()==this.button4){
System.out.println("Afsluiten");
System.exit(0);
}
}
}
I tried using :"button1.setAlignmentX(Component.CENTER_ALIGNMENT);" but that didn't work out very well. Is there any way I can automatically center my buttons to the middle?
How it looks: https://i.stack.imgur.com/Krmhp.jpg