How to put a background image on GridBagLayout - java

I am trying to work with layout managers for the first time, and they are just kicking me in the teeth. I am trying to make a background image and then put buttons on top, using GridBagLayout, if there is a a better layoutmanager please do tell. As for trying to learn how to use layout managers, its very difficult and any learning references would also be much appreciated.
This is what it looks like currently,
I can get the frame to show the full image, but when i use gridlayout manager, it does that
public void addComponentsToPane(Container pane){
BackgroundImage image = new BackgroundImage();
JButton button1, button2, button3, button4, button5;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if(shouldFill){
c.fill = GridBagConstraints.NONE;
}
button1 = new JButton("Button 1");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
button1.setOpaque(false);
pane.add(button1, c);
button2 = new JButton("Button 2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;
button2.setOpaque(false);
pane.add(button2, c);
button3 = new JButton("Button 3");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 2;
c.gridy = 0;
button3.setOpaque(false);
pane.add(button3, c);
button4 = new JButton("Long-Named Button 4");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
pane.add(button4, c);
button5 = new JButton("button 1");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.gridx = 1; //aligned with button 2
c.gridwidth = 2; //2 columns wide
c.gridy = 2; //third row
pane.add(button5, c);
c.ipadx = 800;
c.ipady = 400;
pane.add(image, c);
}
This is what i'm trying to make it look like

Here is one way to do it: using a JLabel as a container with an image (it's a bit unusual but actually works pretty well):
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class TestBackgroundImage {
private static final String BACKHGROUND_IMAGE_URL = "http://www.okyn.org/wp-content/uploads/2013/04/League_of_Legends.jpeg";
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame(TestBackgroundImage.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JLabel mainPanel = new JLabel(backgroundImage) {
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
Dimension lmPrefSize = getLayout().preferredLayoutSize(this);
size.width = Math.max(size.width, lmPrefSize.width);
size.height = Math.max(size.height, lmPrefSize.height);
return size;
}
};
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (int i = 0; i < 5; i++) {
mainPanel.add(new JButton("Button " + (i + 1)), gbc);
}
// Let's put a filler bottom component that will push the rest to the top
gbc.weighty = 1.0;
mainPanel.add(Box.createGlue(), gbc);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestBackgroundImage().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
And the result:
GridBagLayout is unable to handle layering of components (so if you have overlapping gridx/gridy pairs, it won't handle it as layering, I would think that the output is pretty much undetermined.
Try to avoid using gridx/gridy as it make a code hard to maintain. Playing with relative values on gridwidth/gridheight is much easier to maintain.

Check out the Background Panel for a couple of solutions depending on your requirement:
Use a JLabel for painting the image at its actual size.
Use the BackgroundPanel to allow for scaling of the background image.

Related

Location of Java Swing components

I cannot correctly position the components on the form using GridBagLayout. I have tried different variations, but the components are still in the center of the screen.
What I have at the moment
What I want
package View;
import javax.swing.*;
import java.awt.*;
public class Frame extends JFrame {
private JPanel jPanelLeft = new JPanel();
private JPanel jPanelRight = new JPanel();
public Frame(){
setTitle("SCHOOLLLLLLL");
setSize(new Dimension(400,350));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
jPanelLeft.setBackground(Color.BLACK);
jPanelRight.setBackground(Color.RED);
jPanelLeft.add(new JButton("Click on me"));
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.weighty = 1;
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.VERTICAL;
add(jPanelLeft, c);
c.weightx = 1;
c.weighty = 1;
c.gridx = 1;
c.gridy = 0;
c.fill = GridBagConstraints.CENTER;
add(jPanelRight, c);
setVisible(true);
}
}
You could anchor the first container in the WEST location
c.anchor = GridBagConstraints.WEST;

Getting rid of extra spaces between components when the JFrame is resized

I am using the GridBagLayout to arrange some components in a frame.
When the frame is first created, the components have a decent space in between them.
But as soon as I resize the frame there are alot of unwanted space between the components
I tried adjusting the weights and insets as suggested by some users, but it does not seem to fix the problem
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JTextArea;
public class Frame1 extends JFrame {
JLabel one = new JLabel("one");
JLabel two = new JLabel("two");
JLabel three = new JLabel("three");
JTextField oneF = new JTextField(20);
JTextField twoF = new JTextField(20);
JTextField threeF = new JTextField(20);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("menu");
GridBagConstraints c = new GridBagConstraints();
public Frame1() {
setTitle("GridBagLayout Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
menuBar.add(menu);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = c.REMAINDER;
c.fill = c.HORIZONTAL;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(menuBar, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(one, c);
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(oneF, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(two, c);
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(twoF, c);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(three, c);
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(threeF, c);
//setResizable(false);
pack();
setVisible(true);
}
}
ps:- I am new to GUI programming, so please forgive me for any noob mistakes.
edit 1: This is the what I want to have after I am done. I know the currently it does not look anyway near what I have in mind... I am still working on it
Thanks
use an nested layout (combinations of a few LayoutManagers), your picture talks me about,
still you can use GridBagLayout for components placed into left side,
in my code (simplest idea as is possible) JComponents placed on left side can't be resizable because are restricted from LayoutManager`s defaults, more in Oracle tutorial
.
.
painted from SSCCE/MCVE
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyFrame {
private static final long serialVersionUID = 1L;
private JFrame myFrame = new JFrame("Whatever");
private JPanel parentPanel = new JPanel(new BorderLayout(10, 10)) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 400);
}
#Override
public Color getBackground() {
return new Color(255, 000, 000);
}
};
private JPanel leftPanel = new JPanel(/*default is FlowLayout*/) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
#Override
public Color getBackground() {
return new Color(255, 255, 000);
}
};
private JPanel leftChildPanel = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
#Override
public Color getBackground() {
return new Color(255, 255, 225);
}
};
private JPanel rightPanel = new JPanel(new BorderLayout(10, 10)) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 380);
}
#Override
public Color getBackground() {
return new Color(000, 255, 225);
}
};
public MyFrame() {
parentPanel.add(leftPanel, BorderLayout.WEST);
leftPanel.add(leftChildPanel);
parentPanel.add(rightPanel);
myFrame.add(parentPanel);
myFrame.setLocation(150, 150);
myFrame.pack();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new MyFrame();
});
}
}
The idea is to add empty row / columns that will grow to fill the available space:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextField;
public class Frame1 extends JFrame {
JLabel one = new JLabel("one");
JLabel two = new JLabel("two");
JLabel three = new JLabel("three");
JTextField oneF = new JTextField(20);
JTextField twoF = new JTextField(20);
JTextField threeF = new JTextField(20);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("menu");
public Frame1() {
setTitle("GridBagLayout Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0}; //this defines 4 rows
//make 2 last empty row grow
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0,1.0};
//do the same for columns
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 1.0,1.0};
getContentPane().setLayout(gridBagLayout);
menuBar.add(menu);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 5;
c.fill = c.HORIZONTAL;
c.anchor = c.NORTH;
c.insets = new Insets(5, 5, 5, 0);
getContentPane().add(menuBar, c);
//better have a new GridBagConstraints for each component added
GridBagConstraints c1 = new GridBagConstraints();
c1.gridx = 0;
c1.gridy = 1;
c1.gridwidth = 1;
c1.fill = c1.NONE;
c1.anchor = c1.NORTH;
c1.insets = new Insets(5, 5, 0, 5);
getContentPane().add(one, c1);
GridBagConstraints c2 = new GridBagConstraints();
c2.gridx = 1;
c2.gridy = 1;
c2.fill = c2.NONE;
c2.anchor = GridBagConstraints.NORTHWEST;
c2.insets = new Insets(5, 5, 0, 5);
getContentPane().add(oneF, c2);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Frame1();
}
}
EDIT: in response to your edit: use the additional "growing" column for the "cover art"
The problem is your assignments of c.weightx and c.weighty. weightx and weighty determine how extra space is allocated to grid cells in a GridBagLayout when the container is made larger than necessary to accommodate the preferred sizes of the components.
The weightx and weighty should be zero for all cells except those cells which you want to grow larger when the window is made larger.
I have no real idea on how it is supposed to look like, but you could try to set for the labels c.anchor=GridBagConstraints.EAST and c.anchor=GridBagConstraints.WEST for the textfields.
Try also setting c.fill = GridBadConstraints.BOTH.

JTextArea height is only 1 line when using GridBayLayout

I am doing a program that finds words in a text file. I am using GridBagLayout for the position of the elements. When I run the program the text area shows with just one line. Even though it is set JTextArea results = new JTextArea(30, 30)
This is what it shows at the moment:
I am trying to do something like this:
Java code:
public class WordFinder extends JFrame {
private WordList words = new WordList();
private static final int WINDOW_WIDTH = 380;
private static final int WINDOW_HEIGHT = 380;
private static final int TEXT_WIDTH = 30;
private JLabel findLabel = new JLabel("Find:");
private JLabel wordsContaining = new JLabel("words containing");
private JTextField findWord = new JTextField(TEXT_WIDTH);
private JButton clear = new JButton("Clear");
private JTextArea results = new JTextArea(30, 30);
private JScrollPane scroll = new JScrollPane(results);
private JFileChooser chooseFile = new JFileChooser();
private JPanel pane = new JPanel(new GridBagLayout());
public WordFinder() {
super("Word Finder");
// Initialize the menu bar
//initMenu();
results.setEditable(false);
pane.setLayout(new GridBagLayout());
pane.setBorder(new EmptyBorder(15, 20, 0, 10));
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.PAGE_START;
results.setLineWrap(true);
results.setWrapStyleWord(true);
scroll.setViewportView(results);
// Add label "Find"
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(findLabel, c);
// Add text field
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridx = 1;
c.gridy = 0;
pane.add(findWord, c);
// Add clear button
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = .1;
c.gridx = 2;
c.gridy = 0;
pane.add(clear, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 2;
c.insets = new Insets(5, 5, 0, 0);
pane.add(wordsContaining, c);
// Add text area
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 1;
c.gridx = 1;
c.gridy = 3;
c.insets = new Insets(0, 3, 0, 5);
pane.add(scroll, c);
add(pane);
setVisible(true);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run () {
new WordFinder().show();
}
});
}
}
Any ideas in what am I missing? or perhaps I am doing something wrong?
Change c.fill = GridBagConstraints.HORIZONTAL; to c.fill = GridBagConstraints.BOTH;
Use pack instead of setSize
For example
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class WordFinder extends JFrame {
private static final int WINDOW_WIDTH = 380;
private static final int WINDOW_HEIGHT = 380;
private static final int TEXT_WIDTH = 30;
private JLabel findLabel = new JLabel("Find:");
private JLabel wordsContaining = new JLabel("words containing");
private JTextField findWord = new JTextField(TEXT_WIDTH);
private JButton clear = new JButton("Clear");
private JTextArea results = new JTextArea(30, 30);
private JScrollPane scroll = new JScrollPane(results);
private JFileChooser chooseFile = new JFileChooser();
private JPanel pane = new JPanel(new GridBagLayout());
public WordFinder() {
super("Word Finder");
// Initialize the menu bar
//initMenu();
results.setEditable(false);
pane.setLayout(new GridBagLayout());
pane.setBorder(new EmptyBorder(15, 20, 0, 10));
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.PAGE_START;
results.setLineWrap(true);
results.setWrapStyleWord(true);
scroll.setViewportView(results);
// Add label "Find"
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(findLabel, c);
// Add text field
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridx = 1;
c.gridy = 0;
pane.add(findWord, c);
// Add clear button
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = .1;
c.gridx = 2;
c.gridy = 0;
pane.add(clear, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 2;
c.insets = new Insets(5, 5, 0, 0);
pane.add(wordsContaining, c);
// Add text area
c.fill = GridBagConstraints.BOTH;
c.weighty = 1;
c.gridx = 1;
c.gridy = 3;
c.insets = new Insets(0, 3, 0, 5);
pane.add(scroll, c);
add(pane);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new WordFinder().setVisible(true);
}
});
}
}
The problem you're having is caused by a combination of using the fill property GridBagConstraints.HORIZONTAL and setSize. When you use setSize, the size of the container is smaller then the JScrollPane's preferredSize and the layout manager is resorting to it's minimumSize instead.
By using GridBagConstraints.BOTH, you are allowing the layout manager to expand the component to fill the entire available space of the cell, regardless

How do I create spacing in between JButtons?

I am trying to create little main menu for a simple scheduling program right now, but I am having a bit of difficulty having some space in between the buttons. They just stick right next to each other, I would like there to be a gap between each button.
I have tried to use the weightx, weighty commands but nothing seems to change.
I would like to have some blank space between the edges of the GUI and the sides of the buttons, and also between each button.
Here's a screenshot
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Scheduler {
JButton VDay, VWeek, Task, Exit;
JFrame wframe, dframe, tframe;
JLabel head;
public void CreateFrame() {
JFrame frame = new JFrame("Main Menu");
ButtonListener btnlst = new ButtonListener();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.weighty = .25;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
head = new JLabel("The Plain Scheduler");
panel.add(head, c);
c.weightx = 1;
c.weighty = .25;
c.gridx = 0;
c.gridy = 1;
c.gridheight = 2;
c.gridwidth = 3;
VDay = new JButton("View Day");
panel.add(VDay, c);
c.weightx = 1;
c.weighty = .25;
c.gridx = 0;
c.gridy = 3;
c.gridheight = 2;
c.gridwidth = 3;
VWeek = new JButton("View Week");
panel.add(VWeek,c);
c.weightx = 1;
c.weighty = .25;
c.gridx = 0;
c.gridy = 5;
c.gridheight = 2;
c.gridwidth = 3;
Task = new JButton("Assign/Edit Tasks");
panel.add(Task, c);
c.weightx = 1;
c.weighty = .25;
c.gridx = 0;
c.gridy = 7;
c.gridheight = 1;
c.gridwidth = 2;
Exit = new JButton("Exit");
panel.add(Exit, c);
VDay.addActionListener(btnlst);
VWeek.addActionListener(btnlst);
Task.addActionListener(btnlst);
Exit.addActionListener(btnlst);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Scheduler scheduler = new Scheduler();
scheduler.CreateFrame();
}
}
You can use GridBagConstraints#insets to define the amount of spacing/padding which is added to a cell, for example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Scheduler {
JButton VDay, VWeek, Task, Exit;
JFrame wframe, dframe, tframe;
JLabel head;
public void CreateFrame() {
JFrame frame = new JFrame("Main Menu");
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.weighty = .25;
c.insets = new Insets(5, 0, 5, 0);
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
head = new JLabel("The Plain Scheduler");
panel.add(head, c);
VDay = new JButton("View Day");
panel.add(VDay, c);
VWeek = new JButton("View Week");
panel.add(VWeek, c);
Task = new JButton("Assign/Edit Tasks");
panel.add(Task, c);
Exit = new JButton("Exit");
panel.add(Exit, c);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Scheduler scheduler = new Scheduler();
scheduler.CreateFrame();
}
});
}
}

Building a GUI using GridBagLayout (Java)

I am trying to build a GUI for a little Java game using a GridBagLayout. Finally it should look like this:
This is my code:
private GridBagConstraints c;
...
c.gridx = 1;
c.gridy = 0;
c.weightx = 0;
add(playButton, c);
c.gridx = 1;
c.gridy = 1;
c.weightx = 0;
add(optionsButton, c);
c.gridx = 1;
c.gridy = 2;
c.weightx = 0;
add(manualButton, c);
c.gridx = 1;
c.gridy = 3;
c.weightx = 0;
add(exitButton, c);
c.gridx = 0;
c.gridy = 4;
c.weightx = 1;
c.anchor = GridBagConstraints.SOUTHWEST;
add(creditsButton, c);
c.gridx = 2;
c.gridy = 4;
c.weightx = 1;
c.anchor = GridBagConstraints.SOUTHEAST;
add(legalNoticeButton, c);
At the moment it looks like this:
My question is who I can set the two buttons to the bottom without setting the four other bottoms to the top?
Something like this is more or less #Gilbert Le Blanc explained (with minor differences):
Basically use another panel to move your two buttons to the south and spread them to WEST and EAST:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestGridBagLayout {
protected void initUI() {
JFrame frame = new JFrame("test");
final JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridBagLayout());
JButton playButton = new JButton("Play");
JButton optionsButton = new JButton("Options");
JButton manualButton = new JButton("Manual");
JButton exitButton = new JButton("Exit");
JButton creditsButton = new JButton("Credits");
JButton legalNoticeButton = new JButton("Legal");
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
centerPanel.add(playButton, c);
centerPanel.add(optionsButton, c);
centerPanel.add(manualButton, c);
centerPanel.add(exitButton, c);
JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(creditsButton, BorderLayout.WEST);
// Filler component that avoids having the bottom panel too small
bottomPanel.add(new JComponent() {
#Override
public Dimension getPreferredSize() {
return new Dimension(centerPanel.getPreferredSize().width, 0);
}
});
bottomPanel.add(legalNoticeButton, BorderLayout.EAST);
frame.add(centerPanel);
frame.add(bottomPanel, BorderLayout.SOUTH);
frame.pack();
frame.setMinimumSize(frame.getPreferredSize());
frame.setVisible(true);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestGridBagLayout().initUI();
}
});
}
}

Categories

Resources