Java GridBagLayout does not fill frame horizontally - java

I am writing the GUI for a chat program. I can't seem to get the scroller to fill the frame horizontally and vertically and the messageInput to fill the frame horizontally. This is how it looks:
import javax.swing.*;
import java.awt.*;
public class GUI extends JFrame{
private JPanel panel;
private JEditorPane content;
private JTextField messageInput;
private JScrollPane scroller;
private JMenu options;
private JMenuBar mb;
private JMenuItem item;
public GUI(){
/** This is the frame**/
this.setPreferredSize(new Dimension(380,600));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
/** This is where the context shows up **/
content = new JEditorPane();
content.setEditable(false);
/** Scroller that shows up in the context JEditorPane **/
scroller = new JScrollPane(content);
c.weightx = 0.0;
c.weighty = 0.0;
c.gridx = 0;
c.gridy = 0;
panel.add(scroller, c);
/** This is where you type your message **/
messageInput = new JTextField();
c.weightx = 0.0;
c.weighty = 0.0;
c.gridx = 0;
c.gridy = 1;
c.weighty = 0.5;
panel.add(messageInput, c);
mb = new JMenuBar();
options = new JMenu("Options");
mb.add(options);
this.setJMenuBar(mb);
this.add(panel);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new GUI();
}
}

get the scroller to fill the frame horizontally and vertically and the messageInput to fill the frame horizontally.
You want to fill in both directions, so set
c.fill = GridBagConstraints.BOTH; // not HORIZONTAL
The next part is to fix the weights, which will tell how much space to allocate for each component (relatively):
scroller = new JScrollPane(content);
c.weightx = 0.5;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 0;
panel.add(scroller, c);
messageInput = new JTextField();
c.weightx = 0.5;
c.weighty = 0.0;
c.gridx = 0;
c.gridy = 1;
panel.add(messageInput, c);
weightx should be a non-zero value to allow the components to stretch horizontally. weighty should be non-zero for the editor, but not for the text field so that it won't take extra vertical space (in this case you don't need to set c.fill = GridBagConstraints.HORIZONTAL for it).

Related

How to create an ImageIcon with the exact dimensions of a GridBagLayout cell

For a simple GUI I am currently making I want a design similar to this.
The blue and the green area are supposed to be just text and numbers.
The red area is supposed to be an image. Currently, I am creating scaled instances of an Image, create an ImageIcon out of this and then add this to a label to fit an image into different spaces.
The problem is, that without a width I can not create a scaled instance of the picture.
My current GridBagLayout code looks like this:
private static void createAndShowUI()
{
JFrame frame = new JFrame();
JLabel map = new javax.swing.JLabel();
JLabel data = new javax.swing.JLabel();
JLabel menu = new javax.swing.JLabel();
GridBagConstraints c;
frame = new JFrame("Risiko");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.getContentPane().setLayout(new GridBagLayout());
map.setText("MAP");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.75;
c.weighty = 0.75;
frame.getContentPane().add(map, c);
data.setText("DATA");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.weighty = 0.25;
frame.getContentPane().add(data, c);
menu.setText("MENU");
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.gridheight = 2;
c.weightx = 0.25;
frame.getContentPane().add(menu, c);
frame.setVisible(true);
}
I create the three areas and now I want to create an image with the exact width and height of the red area.
So my question is, how can I get the width and height of the red area so I can create a scaled instance of the picture so that it fits into this area?
Test the dynamic layout of the following mre by resizing the frame.
The background image used as background for MapPane is resized to fill the JPanels width and height.
This is achieved by overriding paintComponent:
import java.awt.*;
import java.awt.image.*;
import java.net.URL;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SwingTestPane extends JPanel {
public SwingTestPane() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.rowWeights = new double[]{0.75, .25};
gridBagLayout.columnWeights = new double[]{0.75, 0.25};
setLayout(gridBagLayout);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
JPanel mapPane = new MapPane();
add(mapPane, c);
c.gridx = 0;
c.gridy = 1;
JLabel data = new javax.swing.JLabel("DATA");
JPanel dataPane = new JPanel();
dataPane.add(data);
dataPane.setBackground(Color.YELLOW);
dataPane.setOpaque(true);
add(dataPane, c);
c.gridx = 1;
c.gridy = 0;
c.gridheight = 2;
JLabel menu = new JLabel("MENU");
JPanel menuPane = new JPanel();
menuPane.add(menu);
menuPane.setBackground(Color.GREEN);
menuPane.setOpaque(true);
add(menuPane, c);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400,400);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.getContentPane().add(new SwingTestPane());
frame.pack();
frame.setVisible(true);
}
}
class MapPane extends JPanel {
String imageUrlString = "https://findicons.com/files/icons/345/summer/128/cake.png";
BufferedImage image = null;
MapPane() {
URL url;
try {
url = new URL(imageUrlString);
image = ImageIO.read(url);
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override //Override to paint image as the background
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
}

GridBagLayout formatting for JButtons

My partner and I are writing this program for a game. He used GridBagLayout for our grid and I'm trying to troubleshoot some problems with the grid.
Here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
#SuppressWarnings("serial")
public class NewGame extends JFrame{
private int width = 500, height = 500, xSquares = 4, ySquares = 4;
Font buttonFont = new Font("Times New Roman", Font.PLAIN, 15);
endGame end = new endGame();
public NewGame() {
super("OnO");
// gridbaglayout is flexible but kinda complicated
GridBagLayout Griddy = new GridBagLayout();
this.setLayout(Griddy);
JPanel p = new JPanel();
p.setLayout(Griddy);
this.add(p);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 4;
c.gridheight = 4;
NewBoard board = new NewBoard(xSquares, ySquares);
// board at top left
c.gridx = 0;
c.gridy = 0;
this.add(board, c);
// find a way to make buttons smaller
JButton EndGame = new JButton("End");
EndGame.setBackground(Color.black);
EndGame.setForeground(Color.white);
EndGame.setFont(buttonFont);
EndGame.addActionListener(end);
JButton Undo = new JButton("Undo");
Undo.setBackground(Color.black);
Undo.setForeground(Color.white);
Undo.setFont(buttonFont);
JButton NewGame = new JButton("New Game");
NewGame.setBackground(Color.black);
NewGame.setForeground(Color.white);
NewGame.setFont(buttonFont);
// fit 3
c.gridwidth = 1;
c.gridheight = 1;
c.gridy = 3;
c.fill = GridBagConstraints.HORIZONTAL;
p.add(EndGame, c);
c.gridx = 2;
c.fill = GridBagConstraints.HORIZONTAL;
p.add(Undo, c);
c.gridx = 3;
c.fill = GridBagConstraints.HORIZONTAL;
p.add(NewGame, c);
this.setPreferredSize(new Dimension(width, height));
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
this.setLocation(450, 30);
this.setVisible(true);
}
public class endGame implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
}
public class newGame implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
}
When this code is run with the other classes in our program, the endGame, Undo, and NewGame buttons overlap with the board:
I want to find a way to display the 3 buttons either above or below the board in its individual space, but I've tinkered with the code for a long time and can't find the solution yet. I'm not sure what I should be doing here.
First of all, variable names should NOT start with an upper case character. Learn and follow Java naming conventions.
I want to find a way to display the 3 buttons either above or below the board
Simplest solution is to not use a GridBagLayout for the frame.
Just use the default BorderLayout of the frame. Then you can use a JPanel with the FlowLayout for your buttons, and a GridLayout for your board panel.
The basic logic would be:
JPanel buttons = new JPanel();
buttons.add(endGame);
buttons.add(undo);
buttons.add(newGame);
this.add(button, BorderLayout.PAGE_START);
NewBoard board = new NewBoard(xSquares, ySquares);
this.add(board, BorderLayout.CENTER);
By default a JPanel uses a FlowLayout so the buttons will be displayed on a single row.
Read the Swing tutorial on Layout Managers for more information and working examples to better understand how this suggestion works.

how to put components in the center in a CardLayout panel

I have a frame that has couple of panels and they change by CardLayout.
Inside each panel i will have different components. To design the GUI of the panel I used GridBagLayout. But the problem is any component or Layout I use for these paneles, they all stay at the top of the page. So basically the panel size of the CardLayout is some small amount of the frame. I want to make the sub panel size as large as the main CardLayout size.
Code for main CardLayout:
public class MainPanel extends JPanel {
private CardLayout cl = new CardLayout();
private JPanel panelHolder = new JPanel(cl);
public MainPanel() {
NewSession session = new NewSession(this);
ChooseSource chooseSource = new ChooseSource(this);
panelHolder.add(session, "1");
panelHolder.add(chooseSource, "2");
cl.show(panelHolder, "dan");
add(panelHolder);
}
public void showPanel(String panelIdentifier){
cl.show(panelHolder, panelIdentifier);
}
}
A sub panel:
public class ChooseSource extends JPanel {
MainPanel ob2;
JButton btn;
JLabel label;
JTextField field;
public ChooseSource(MainPanel mainPanel){
this.ob2 = mainPanel;
btn = new JButton("Browse");
label = new JLabel("Folder ");
field = new JTextField();
btn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
ob2.showPanel("1");
}
});
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.ipady = 20;
c.gridheight = 2;
add(btn, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
c.ipady = 10;
c.gridheight = 1;
c.insets = new Insets(0,10,0,0);
add(label, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
c.ipady = 0;
c.gridheight = 1;
c.insets = new Insets(0,10,0,0);
add(field, c);
}
}
The left image shows how it is not, and right one is the one I am trying to make. basically I want to have access to all the available space of the panel.
Any idea?
Change the layout manager of MainPanel to something like BorderLayout or GridBagLayout

Vertical filling of GridBagLayout in Java does not work

I am having troubles getting the layout right.
I have a Class which extends JFrame and has a JPanel which has a the GridBagLayout as layout manager. I want 4 buttons which should be layout in this way
Somehow the vertical filling does not work.
I tried various ways but can't figure out how to make this work.
Sorry if this is a noob question, but tried it for more than an hour without any change :/
public class ButtonPanel extends JFrame {
private static final long serialVersionUID = 1L;
public ButtonPanel() {
this.setSize(800, 600);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
frame();
}
JButton objectsBtn = new JButton("Objekte"); //TODO Strings einfügen
JButton tenantBtn = new JButton("Mieter"); //TODO Strings einfügen
JButton ownerBtn = new JButton("Eigentümer"); //TODO Strings einfügen
JButton optionsBtn = new JButton("Einstellungen"); //TODO Strings einfügen
JPanel panel = new JPanel();
public void frame(){
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
c.fill = GridBagConstraints.BOTH;
c.gridwidth = GridBagConstraints.RELATIVE;
c.gridheight = GridBagConstraints.RELATIVE;
//Elemente
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 0;
panel.add(objectsBtn, c);
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 1;
c.gridy = 0;
panel.add(optionsBtn, c);
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 1;
panel.add(ownerBtn, c);
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 1;
c.gridy = 1;
panel.add(tenantBtn, c);
this.add(panel);
objectsBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
new Object();
}
});
ownerBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//TODO Eigentümer erstellen
}
});
}
}
greets
THE-E
EDIT: Found the bug
I used Seaglass as Look and Feel in the main-method
//Set Theme
try {
UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
It works fine with the default Look and Feel Theme.
I have added the answer in the first post. It was a bug caused by the LookAndFeel skin. :/
greets
THE-E

Java Swing - realising a layout with LayeredPane

I have a question regarding making a specific Layout, first I'll show examples then I will add some extra clarification.
Layout when Friends and Messages are closed:
Layout when Friends and Messages are opened:
I intend to make this layout with Java Swing.
My intention is to firstly have the Frame divided in three areas, the top menu row, the main panel and the bottom menu row.
I was thinking of using a BorderLayout for this part.
Then the Friends and Messages buttons should be toggle button's, and on toggle they should show an overlay on top of the mainpanel (or whatever is there), containing a friend list and a message area. I realised I need to use a LayeredPane somehow for this.
Another important part is that the Layout should be viewable in any size, that is the user may resize the application and it will be used on a various amount of resolutions, so I don't really want anything with a fixed width and height.
But I am really lost as how to combine this, so therefore I ask your help.
Hopefully I have explained enough about the situation.
Regards.
this could be about overlay, because JPanel can contains other JComponents
use JLayer (Java7) based on JXLayer(Java6),
use GlassPane with JComponents layed to rellative to....
easiest could be to use JDialog(undecorated) layed to Point (setLocation(int, int)), setVisible() must be wrapped into invokeLater
I will use gridBagLayout.
Here is small example including button which hide your yellow panels:
package Core;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridBagLayoutDemo {
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
add1row(pane);
addmainRow(pane);
addLastRow(pane);
}
private static void addLastRow(Container pane) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 3;
c.anchor = GridBagConstraints.PAGE_END;
JPanel bottonPanel = new JPanel();
bottonPanel.setBackground(Color.BLUE);
bottonPanel.setLayout(new GridBagLayout());
pane.add(bottonPanel, c);
JPanel messagePanel = new JPanel();
messagePanel.setBackground(Color.GRAY);
messagePanel.add(new JLabel("MESSAGES"));
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_END;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
bottonPanel.add(messagePanel, c);
}
private static void addmainRow(Container pane) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.CENTER;
JPanel mainManel = new JPanel();
mainManel.setBackground(Color.GREEN);
mainManel.setLayout(new GridBagLayout());
pane.add(mainManel, c);
final JPanel friendListPanel = new JPanel();
friendListPanel.setBackground(Color.YELLOW);
friendListPanel.add(new JLabel("FRIEND LIST"));
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.FIRST_LINE_END;
mainManel.add(friendListPanel, c);
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 1;
c.weightx = 0;
c.weighty = 0;
c.anchor = GridBagConstraints.CENTER;
JButton button = new JButton("On/Off");
mainManel.add(button, c);
final JPanel messageAreaPanel = new JPanel();
messageAreaPanel.setBackground(Color.YELLOW);
messageAreaPanel.add(new JLabel("MESSAGE PANEL"));
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 2;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.LAST_LINE_END;
mainManel.add(messageAreaPanel, c);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
friendListPanel.setVisible(!friendListPanel.isVisible());
messageAreaPanel.setVisible(!messageAreaPanel.isVisible());
}
});
}
private static void add1row(Container pane) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.PAGE_START;
Panel headerPanel = new Panel();
headerPanel.setLayout(new GridBagLayout());
headerPanel.setBackground(Color.BLUE);
pane.add(headerPanel, c);
JPanel quitPanel = new JPanel();
quitPanel.setBackground(Color.GRAY);
quitPanel.add(new JLabel("QUIT"));
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_START;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
headerPanel.add(quitPanel, c);
JPanel friendsPanel = new JPanel();
friendsPanel.setBackground(Color.GRAY);
friendsPanel.add(new JLabel("FRIENDS"));
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_END;
c.gridx = 1;
c.gridy = 0;
headerPanel.add(friendsPanel, c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame);
// uncoment to use full screen
// frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
frame.setSize(new Dimension(400, 400));
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Categories