0

I will place these buttons in the center of the frame and above each other, like this.

                                     BUTTON
                                     BUTTON
                                     BUTTON

I've searched multiple topics on this forum but everything I tried didn't work for so far. I hope that somebody has the solution.

This is my code for so far:

package ípsen1;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;

public class Paneel extends JPanel implements ActionListener {
Image achtergrond;
private JButton spelHervatten;
private JButton spelOpslaan;
private JButton spelAfsluiten;


public Paneel(){
    //buttons   
    spelHervatten = new JButton("Spel hervatten");
    spelHervatten.setPreferredSize(new Dimension(380, 65));

    spelOpslaan = new JButton("Spel opslaan");
    spelOpslaan.setPreferredSize(new Dimension(380, 65));

    spelAfsluiten = new JButton("Spel afsluiten");  
    spelAfsluiten.setPreferredSize(new Dimension(380, 65));


    //object Paneel luistert naar button events
    spelAfsluiten.addActionListener(this);

    add (spelHervatten);
    add (spelOpslaan);
    add (spelAfsluiten);
    }

public void paintComponent(Graphics g) {
    //achtergrond afbeelding zetten
    achtergrond = Toolkit.getDefaultToolkit().getImage("hout.jpg");
    //screensize
    g.drawImage(achtergrond, 0,0, 1024,768,this);
}

    //actie na klik op button
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() == spelAfsluiten){
                    System.out.println("Spel afsluiten");
                    System.exit(0);
                    }
                }
            }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user3510337
  • 1
  • 1
  • 1
  • 1
  • `spelOpslaan.setPreferredSize(new Dimension(380, 65));` See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) – Andrew Thompson Apr 08 '14 at 11:38
  • `public void paintComponent(Graphics g) { //achtergrond afbeelding zetten achtergrond = Toolkit.getDefaultToolkit().getImage("hout.jpg");..` 1) The 1st line should be `super.paintComponent(g);` 2) `achtergrond afbeelding zetten` Comments that aren't in English are noise on SO. 3) Don't load the image in the `paintXxx(..)` methods! Instead load it at start-up and store it as a class attribute. – Andrew Thompson Apr 08 '14 at 11:41
  • For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete and Verifiable Example). – Andrew Thompson Apr 08 '14 at 11:42

5 Answers5

8

You could use a GridBagLayout

Buttons

setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;

add(new JButton("Button"), gbc);
add(new JButton("Button"), gbc);
add(new JButton("Button"), gbc);
add(new JButton("Button"), gbc);

See How to Use GridBagLayout for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

A BoxLayout might be what you're after. You can specify that you want to add components along the y-axis in the constructor for that particular layout manager.

You could add this line to the constructor of your Paneel class.

this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

As for center-aligning everything, I don't know if it's good practice but you can set the horizontal alignment for each of your buttons individually. Example:

spelHervatten.setAlignmentX(CENTER_ALIGNMENT);
PakkuDon
  • 1,627
  • 4
  • 22
  • 21
1

Uses a GridLayout for a single column of buttons of equal width.

The buttons stretch as the window's size increases. To maintain the button size, put the GridLayout as a single component into a GridBagLayout with no constraint. It will be centered.

enter image description here

The size of the buttons is increased by setting a margin.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

/*
 * Uses a GridLayout for a single column of buttons of equal width.
 * The buttons stretch as the window's size increases.  To maintain
 * the button size, put the GridLayout as a single component into a 
 * GridBagLayout with no constraint.  It will be centered.
 */
public class CenteredSingleColumnOfButtons {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                // the GUI as seen by the user (without frame)
                JPanel gui = new JPanel(new GridLayout(0,1,10,10));
                gui.setBorder(new EmptyBorder(20,30,20,30));

                String[] buttonLabels = {
                    "Spel hervatten",
                    "Spel opslaan",
                    "Spel afsluiten"
                };

                Insets margin = new Insets(20,150,20,150);
                JButton b = null;
                for (String s : buttonLabels) {
                    b = new JButton(s);
                    b.setMargin(margin);
                    gui.add(b);
                }

                JFrame f = new JFrame("Centered Single Column of Buttons");
                f.add(gui);
                // Ensures JVM closes after frame(s) closed and
                // all non-daemon threads are finished
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                // See http://stackoverflow.com/a/7143398/418556 for demo.
                f.setLocationByPlatform(true);

                // ensures the frame is the minimum size it needs to be
                // in order display the components within it
                f.pack();
                f.setMinimumSize(f.getSize());
                // should be done last, to avoid flickering, moving,
                // resizing artifacts.
                f.setVisible(true);
                System.out.println(b.getSize());
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0

I thought there is no way to do that.

You should get size of Panel/Frame then calculate manually to find to center position for your button.

tana
  • 585
  • 1
  • 5
  • 16
  • 1
    Recommendations of absolute layouts don't produce professional or long term sustainable results, especially when there are plenty of other, simpler solutions that would work across platforms – MadProgrammer Apr 08 '14 at 10:15
0

Rephrased some parts:

You might want to try to put the buttons in JFrame's "wind direction"-style BorderLayout: http://www.leepoint.net/notes-java/GUI/layouts/20borderlayout.html

Just create a block in the CENTER with one EAST and WEST block with a certain size around it. Then insert the buttons inside of the center block. If you don't want them to be the full size, just add another EAST and WEST.

thinkgruen
  • 929
  • 10
  • 15
  • Until you want to add more than three buttons or don't want to them to expand the full width or want them to be equal height...interesting idea... – MadProgrammer Apr 08 '14 at 10:14