I've attached a screenshot for which the following Border legend applies:
Yellow = JPanel with BorderLayout
Blue = JPanel with GridBagLayout
Fuchsia = JPanel with FlowLayout
There are two panels not blocked out in colors that warrant mentioning:
1) The title panel where the word "Primary" is displayed; this panel is at BorderLayout.NORTH in "Yellow" panel.
2) The image panel where the image of the device is located; this panel is a sibling to "Fuchsia"
"Blue" is at BorderLayout.CENTER in "Yellow" while "Fuchsia" and the image panel are given the following constraints:
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.insets = new Insets(0, 10, 0, 0);
c.fill = GridBagConstraints.BOTH;
//"Blue".add(imagePanel, c);
c.weighty = 0.80;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
//"Blue".add("Fuchsia", c);
As you can probably tell from the image, I'm trying to get rid of the "wasted" space in "Blue" right below "Fuchsia". I don't seem to be able to do it with GridBagConstraints, so am I just using the wrong LayoutManager? It looks to me like "Blue", who is at CENTER in the BorderLayout is just giving each child JPanel half of the available space and reserving the remainder space instead of contracting upward. What am I missing here? Is this simply a matter of setting a preferred or maximum size on "Fuchsia"? it doesn't seem like that will get me where I want to be, since the border around "Fuchsia" (which is covered by my color coding) is where I want the end of the component to be.
Have a look at this output, from this code example :
import java.awt.*;
import javax.swing.*;
public class LayoutTest
{
private void displayGUI()
{
JFrame frame = new JFrame("Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.YELLOW);
contentPane.setLayout(new BorderLayout(2, 2));
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel headingLabel = new JLabel("Primary");
topPanel.add(headingLabel);
contentPane.add(topPanel, BorderLayout.PAGE_START);
JPanel centerPanel = new JPanel();
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.BLUE);
centerPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 0;
JPanel imagePanel = new JPanel();
JLabel imageLabel = null;
try
{
imageLabel = new JLabel(
new ImageIcon(
new java.net.URL(
"http://pscode.org/"
+ "tame/screenshot/"
+ "landscape/slider1.gif")));
}
catch(Exception e)
{
e.printStackTrace();
}
imagePanel.add(imageLabel);
centerPanel.add(imagePanel, gbc);
JPanel detailsPanel = new JPanel();
detailsPanel.setOpaque(true);
detailsPanel.setBackground(Color.WHITE);
detailsPanel.setBorder(
BorderFactory.createEmptyBorder(
5, 5, 5, 5));
detailsPanel.setLayout(new GridLayout(0, 1, 5, 5));
JLabel statusLabel = new JLabel("Chassis Status : ");
JLabel usageLabel = new JLabel("Bandwidth Usage : ");
JLabel fanLabel = new JLabel("Fan Status : ");
detailsPanel.add(statusLabel);
detailsPanel.add(usageLabel);
detailsPanel.add(fanLabel);
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 0.8;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridheight = 3;
centerPanel.add(detailsPanel, gbc);
contentPane.add(centerPanel, BorderLayout.CENTER);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new LayoutTest().displayGUI();
}
});
}
}
Without using GridBagLayout could be
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class NestedLayout {
private JFrame frame = new JFrame();
private JPanel yellowNorthPanel = new JPanel();
private JPanel yellowPanel = new JPanel();
private JPanel bluePanel = new JPanel();
private JPanel fuchsiaTopPanel = new JPanel();
private JPanel fuchsiaBottonPanel = new JPanel();
public NestedLayout() {
yellowNorthPanel.setBorder(new LineBorder(Color.yellow, 5));
yellowPanel.setLayout(new BorderLayout());
yellowPanel.setBorder(new LineBorder(Color.yellow, 5));
bluePanel.setLayout(new BorderLayout(5, 5));
bluePanel.setBorder(new LineBorder(Color.blue, 5));
fuchsiaTopPanel.setBorder(new LineBorder(Color.cyan, 5));
fuchsiaBottonPanel.setBorder(new LineBorder(Color.cyan, 5));
bluePanel.add(fuchsiaTopPanel, BorderLayout.NORTH);
bluePanel.add(fuchsiaBottonPanel);
yellowPanel.add(bluePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(yellowNorthPanel, BorderLayout.NORTH);
frame.add(yellowPanel);
//frame.pack();
frame.setSize(400, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new NestedLayout();
}
});
}
}
Related
I'm a little lost here, when I run the program the buttons are in the middle of the input and not directly on the bottom aligned with it. I'm not sure what I'm doing wrong. I'm also trying to find out how to get statistics for my input like min and max value, and average word size. I'm a little lost, thanks!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.Arrays;
public class CopyTextPanel extends JPanel
{
private JTextField input;
private JLabel output, inlabel, outlabel;
private JButton compute, clear;
private JPanel panel, panel1, panel2;
public CopyTextPanel()
{
setLayout (new BoxLayout(this, BoxLayout.Y_AXIS));
inlabel = new JLabel("Input: ");
outlabel = new JLabel("Text Statistics Result: ");
input = new JTextField (50);
output = new JLabel();
compute = new JButton("Compute Statistics");
compute.addActionListener (new ButtonListener());
clear = new JButton("Clear Text");
clear.addActionListener (new ButtonListener());
panel = new JPanel();
panel1 = new JPanel();
panel2 = new JPanel();
output.setMaximumSize (new Dimension(500, 30));
output.setMinimumSize (new Dimension(500, 30));
panel.setMaximumSize (new Dimension(500, 30));
panel.setMinimumSize (new Dimension(500, 30));
panel.setBackground(Color.gray);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(inlabel);
panel.add(input);
panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));
panel1.add(compute);
panel1.add(clear);
add (Box.createRigidArea (new Dimension(0, 10)));
panel2.setLayout(new BoxLayout(panel2, BoxLayout.X_AXIS));
panel2.add(outlabel);
panel2.add(output);
setMaximumSize (new Dimension(600, 250));
setMinimumSize (new Dimension(600, 250));
setBackground(Color.white);
add (panel);
add (panel1);
add (panel2);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
String inputText = input.getText();//sets what is typed by the user
to a String object
String[] splitted = inputText.trim().split("\\p{javaSpaceChar}
{1,}");//makes a String array, and trims all the whitespaces from the user
input
int numberofWords = splitted.length;//it then sets splitted length
to an integer
String numow = Integer.toString(numberofWords);// finally it makes
the numberofwords int into a string
Arrays.sort(splitted);
if (event.getSource()==compute)//if the user presses the compute
button
{
output.setText (numow + " words; " );//the output is the string
of integers of how many words were typed
}
else//if the user presses another button
input.setText(" "); // clear text filed after copying
}
}
}
So based on the desired result...
I would recommend considering using a series of panels, dedicated to generating the layout requirements for each row, then wrapping those together into a single container.
For my money, GridBagLayout presents the most flexible option, while also presenting one of the more complicated at the same time.
This example focuses solely on the layout requirements, you'll have to figure out how to apply the functionality to it later.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() throws HeadlessException {
setBorder(new EmptyBorder(5, 5, 5, 5));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
JPanel fieldPane = new JPanel(new GridBagLayout());
JTextField inputField = new JTextField("Computer Science 1");
fieldPane.add(new JLabel("Input Text:"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
fieldPane.add(inputField, gbc);
JPanel buttonPane = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
buttonPane.add(new JButton("Computer Statistics"), gbc);
gbc.anchor = GridBagConstraints.LINE_START;
gbc.weightx = 1;
buttonPane.add(new JButton("Clear Text"), gbc);
JPanel resultsPane = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
resultsPane.add(new JLabel("Text Statistics Result:"));
gbc.anchor = GridBagConstraints.LINE_START;
gbc.weightx = 1;
resultsPane.add(new JLabel("3 words"), gbc);
gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(fieldPane, gbc);
add(buttonPane, gbc);
add(resultsPane, gbc);
}
}
}
I strongly recommend having a look at Laying Out Components Within a Container for more details about how various layout managers work
You should use Layouts such as BorderLayout that might help you.
Change the JPanels by doing panel.add(new JButton("East"),BorderLayout.EAST);
etc.. I hope it helps. If you dont use layouts they will end up randomized.
So I'm trying to copy the layout of this website.
Website Pinterest Log In
Here's some what I have already done.
I'm using "null" for my layout.
I also put an actionlistener on my button which shows another frame.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Frame {
public static void main (String [] args) {
JFrame frame = new JFrame("Pinterest");
frame.setVisible(true);
frame.setSize(1300,750);
JPanel panel = new JPanel();
frame.add(panel);
JLabel name = new JLabel("Log in to Pinterest");
name.setBounds(500, 96, 300, 100);
name.setFont(new Font("Tahoma", Font.PLAIN, 28));
JTextField text1 = new JTextField(15);
text1.setBounds(500, 450, 300, 40);
JTextField text2 = new JTextField(15);
text2.setBounds(500, 350, 300, 40);
JButton button = new JButton("Log In");
button.setBounds(560,550, 200,30 );
panel.setLayout(null);
panel.add(name);
panel.add(text1);
panel.add(text2);
panel.add(button);
button.addActionListener(new Action1());
}
static class Action1 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JFrame frame2= new JFrame("Pinterest");
frame2.setVisible(true);
frame2.setSize(1300,750);
}}
Every time I would run this in my JCreator it would only show my frame. Then I have to maximize it to view the components but after I maximize it then minimize it doesn't hide anymore.
After I maximize the frame.
What is wrong with my code?
Does my code works on yours smoothly? does it shows?
How can I hide the first frame after clicking the button?
I'm having a hard time putting icon on the frame too.
Thanks for the help.
There are a number of basic mistakes
null layouts. Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Making the frame visible before you've finished updating the UI. In most cases this can be fixed with revalidate, but since that causes the layout managers to recalculate their layouts, it's pointless when you're using null layouts
The simple answer is, use layout managers. The longer answer is more complicated.
You have three distinct areas, the "login with" group, the "field" group and (what I like to term) the "action" group. Each of these have there own requirements and functionality, it's best to try a seperate them if you can.
This will allow to apply functionality to each group or class which is unique to that group/class and reduce a lot of management head aches
The following examples focus on the layout, it does not focus on how you would then connect the functionality, this would be achieved simply through the use of an Observer Pattern, perhaps like ActionListener
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
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.JPasswordField;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new LoginPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class LoginPane extends JPanel {
public LoginPane() {
setBackground(Color.WHITE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(4, 20, 4, 20);
JLabel title = new JLabel("Log in to Pinterest");
title.setFont(title.getFont().deriveFont(Font.BOLD, 18f));
title.setBorder(new EmptyBorder(10, 0, 10, 0));
add(title, gbc);
add(new GroupPane(), gbc);
gbc.insets = new Insets(4, 0, 4, 0);
add(new JSeparator(JSeparator.HORIZONTAL), gbc);
gbc.insets = new Insets(4, 20, 4, 20);
add(new FieldPane(), gbc);
gbc.insets = new Insets(4, 0, 0, 0);
add(new ActionPane(), gbc);
}
}
public class GroupPane extends JPanel {
public GroupPane() {
setOpaque(false);
JPanel fbPane = new JPanel();
JPanel goPane = new JPanel();
JPanel twPane = new JPanel();
fbPane.setBackground(Color.RED);
goPane.setBackground(Color.BLUE);
twPane.setBackground(Color.CYAN);
fbPane.add(makeLabel("Log in with Facebook"));
goPane.add(makeLabel("Log in with Google"));
twPane.add(makeLabel("Log in with Twitter"));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(4, 0, 4, 0);
add(fbPane, gbc);
add(goPane, gbc);
add(twPane, gbc);
}
protected JLabel makeLabel(String text) {
JLabel label = new JLabel(text);
label.setForeground(Color.WHITE);
label.setFont(label.getFont().deriveFont(Font.BOLD, 14f));
return label;
}
}
public class FieldPane extends JPanel {
private JTextField email;
private JPasswordField password;
public FieldPane() {
setOpaque(false);
email = new JTextField(10);
password = new JPasswordField(10);
email.setBackground(new Color(225, 225, 225));
password.setBackground(new Color(225, 225, 225));
Font font = email.getFont().deriveFont(Font.PLAIN, 24f);
email.setFont(font);
password.setFont(font);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(4, 0, 4, 0);
add(email, gbc);
add(password, gbc);
JLabel label = new JLabel("Are you a business? Get started here");
label.setFont(label.getFont().deriveFont(Font.PLAIN, 10f));
gbc.insets.left = 4;
add(label, gbc);
}
}
public class ActionPane extends JPanel {
public ActionPane() {
setBorder(new EmptyBorder(10, 20, 10, 20));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.WEST;
add(makeLabel("Forgot your password?"), gbc);
gbc.gridy++;
add(makeLabel("Sign up now"), gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.gridheight = 2;
gbc.ipady = 10;
gbc.anchor = GridBagConstraints.EAST;
JButton login = new JButton("Log in");
add(login, gbc);
}
protected JLabel makeLabel(String text) {
JLabel label = new JLabel(text);
label.setForeground(Color.DARK_GRAY);
return label;
}
}
}
Take a look at Laying Out Components Within a Container and How to Use GridBagLayout. The LoginPane could also make use of a GridLayout, see for more details
So what I am trying to do is create this:
I am using a gridbag layout and here is what I have so far:
public class board {
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JPanel leftTop = new JPanel();
leftTop.setPreferredSize(new Dimension(251,300));
leftTop.setBackground(Color.black);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(leftTop, c);
JPanel middleTop = new JPanel();
middleTop.setPreferredSize(new Dimension(251,200));
middleTop.setBackground(Color.green);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
pane.add(middleTop, c);
JPanel rightTop = new JPanel();
rightTop.setPreferredSize(new Dimension(251,600));
rightTop.setBackground(Color.blue);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 0;
pane.add(rightTop, c);
JPanel leftBottom = new JPanel();
leftBottom.setPreferredSize(new Dimension(251,300));
leftBottom.setBackground(Color.red);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
pane.add(leftBottom, c);
JPanel middleBottom = new JPanel();
middleBottom.setPreferredSize(new Dimension(251,400));
middleBottom.setBackground(Color.yellow);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
pane.add(middleBottom, c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
It creates something like:
How would I push up the panels so they are touching each other like in my first picture. I looked through the GridBagConstraints but I could not find anything that looked like it would work. Thanks!
Instead of trying to solve the complete layout problem with one layout manager, it's often simpler to nest layouts. For example, your example code could be modified to use a horizontal grid layout (to keep the columns equal width - I don't actually know if you want to force that. If not, then FlowLayout or BoxLayout would be better), and the columns use a BoxLayout each:
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class board {
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridLayout(1, 0));
JPanel left = new JPanel();
pane.add(left);
left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS));
JPanel leftTop = new JPanel();
leftTop.setPreferredSize(new Dimension(125, 150));
leftTop.setBackground(Color.black);
left.add(leftTop);
JPanel leftBottom = new JPanel();
leftBottom.setPreferredSize(new Dimension(125, 150));
leftBottom.setBackground(Color.red);
left.add(leftBottom);
JPanel middle = new JPanel();
pane.add(middle);
middle.setLayout(new BoxLayout(middle, BoxLayout.Y_AXIS));
JPanel middleTop = new JPanel();
middleTop.setPreferredSize(new Dimension(125, 100));
middleTop.setBackground(Color.green);
middle.add(middleTop);
JPanel middleBottom = new JPanel();
middleBottom.setPreferredSize(new Dimension(125, 200));
middleBottom.setBackground(Color.yellow);
middle.add(middleBottom);
JPanel right = new JPanel();
right.setPreferredSize(new Dimension(125, 300));
right.setBackground(Color.blue);
pane.add(right);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
Results in:
(I modified the preferred sizes a bit to make the image smaller. As a further note it's usually better to override getPreferredSize() rather than use setPreferredSize(); setPreferredSize() is convenient for the quick example though)
I want the various components to spread out and fill the entire window.
Have you tried anything else? Yes, I tried GridLayout but then the buttons look huge. I also tried pack() which made the window small instead. The window should be 750x750 :)
What I was trying is this:
These 4 buttons on the top as a thin strip
The scroll pane with JPanels inside which will contain all the video conversion tasks. This takes up the maximum space
A JPanel at the bottom containing a JProgressBar as a thin strip.
But something seems to have messed up somewhere. Please help me solve this
SSCCE
import java.awt.*;
import javax.swing.*;
import com.explodingpixels.macwidgets.*;
public class HudTest {
public static void main(String[] args) {
HudWindow hud = new HudWindow("Window");
hud.getJDialog().setSize(750, 750);
hud.getJDialog().setLocationRelativeTo(null);
hud.getJDialog().setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton addVideo = HudWidgetFactory.createHudButton("Add New Video");
JButton removeVideo = HudWidgetFactory.createHudButton("Remove Video");
JButton startAll = HudWidgetFactory.createHudButton("Start All Tasks");
JButton stopAll = HudWidgetFactory.createHudButton("Stop All Tasks");
buttonPanel.add(addVideo);
buttonPanel.add(startAll);
buttonPanel.add(removeVideo);
buttonPanel.add(stopAll);
JPanel taskPanel = new JPanel(new GridLayout(0,1));
JScrollPane taskScrollPane = new JScrollPane(taskPanel);
IAppWidgetFactory.makeIAppScrollPane(taskScrollPane);
for(int i=0;i<10;i++){
ColorPanel c = new ColorPanel();
c.setPreferredSize(new Dimension(750,100));
taskPanel.add(c);
}
JPanel progressBarPanel = new JPanel();
JComponent component = (JComponent) hud.getContentPane();
component.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
Insets in = new Insets(2,2,2,2);
gbc.insets = in;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 10;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
component.add(buttonPanel,gbc);
gbc.gridy += 1;
gbc.gridheight = 17;
component.add(taskScrollPane,gbc);
gbc.gridy += 17;
gbc.gridheight = 2;
component.add(progressBarPanel,gbc);
hud.getJDialog().setVisible(true);
}
}
Use this
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridbagConstraints.BOTH
Why not simply place three JPanels on top of one JPanel with BorderLayout as Layout Manager, where the middle JPanel with all custom panels with their respective sizes can be accommodated inside a JScrollPane, as shown in the below example :
import javax.swing.*;
import java.awt.*;
import java.util.Random;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 5/17/13
* Time: 6:09 PM
* To change this template use File | Settings | File Templates.
*/
public class PlayerBase
{
private JPanel contentPane;
private JPanel buttonPanel;
private JPanel centerPanel;
private CustomPanel[] colourPanel;
private JPanel progressPanel;
private JButton addVideoButton;
private JButton removeVideoButton;
private JButton startAllButton;
private JButton stopAllButton;
private JProgressBar progressBar;
private Random random;
public PlayerBase()
{
colourPanel = new CustomPanel[10];
random = new Random();
}
private void displayGUI()
{
JFrame playerWindow = new JFrame("Player Window");
playerWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new JPanel(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
addVideoButton = new JButton("Add New Video");
removeVideoButton = new JButton("Remove Video");
startAllButton = new JButton("Start all tasks");
stopAllButton = new JButton("Stop all tasks");
buttonPanel.add(addVideoButton);
buttonPanel.add(removeVideoButton);
buttonPanel.add(startAllButton);
buttonPanel.add(stopAllButton);
contentPane.add(buttonPanel, BorderLayout.PAGE_START);
JScrollPane scroller = new JScrollPane();
centerPanel = new JPanel(new GridLayout(0, 1, 2, 2));
for (int i = 0; i < colourPanel.length; i++)
{
colourPanel[i] = new CustomPanel(new Color(
random.nextInt(255), random.nextInt(255)
, random.nextInt(255)));
centerPanel.add(colourPanel[i]);
}
scroller.setViewportView(centerPanel);
contentPane.add(scroller, BorderLayout.CENTER);
progressPanel = new JPanel(new BorderLayout(5, 5));
progressBar = new JProgressBar(SwingConstants.HORIZONTAL);
progressPanel.add(progressBar);
contentPane.add(progressPanel, BorderLayout.PAGE_END);
playerWindow.setContentPane(contentPane);
playerWindow.pack();
//playerWindow.setSize(750, 750);
playerWindow.setLocationByPlatform(true);
playerWindow.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new PlayerBase().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel
{
public CustomPanel(Color backGroundColour)
{
setOpaque(true);
setBackground(backGroundColour);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(750, 100));
}
}
OUTPUT :
Hi I am trying to add 2 JPanel's to a JFrame that take the full width and height of the JFrame.I managed to add them with GridBagLayout() but I can't seem to set the size of the JPanels using the setsize().I have also tryied to used ipady and ipadx while that seemed to work at first after I aded some buttons the whole layout became a mess.Here is my code:
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setVisible(true);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
tradeframe.setLayout(new GridBagLayout());
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
GridBagConstraints a = new GridBagConstraints();
a.gridx = 0;
a.gridy = 0;
a.weightx = 360;
a.weighty = 300;
//a.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P1panel , a);
GridBagConstraints b = new GridBagConstraints();
b.gridx = 1;
b.gridy = 0;
b.weightx = 360;
b.weighty = 300;
// b.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P2panel , b);
How can I make that each JPanel is 300px width and 400px in height?
for GridBaglayout you have to set
fill
anchor
weightx and weighty
gridx / gridy (depend of orientations)
then is possible for example
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderPanels extends JFrame {
private static final long serialVersionUID = 1L;
public BorderPanels() {
setLayout(new GridBagLayout());// set LayoutManager
GridBagConstraints gbc = new GridBagConstraints();
JPanel panel1 = new JPanel();
Border eBorder = BorderFactory.createEtchedBorder();
panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridx = gbc.gridy = 0;
gbc.gridwidth = gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = gbc.weighty = 20;
add(panel1, gbc); // add compoenet to the COntentPane
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "60pct"));
gbc.gridy = 1;
gbc.weightx = gbc.weighty = 60;
//gbc.insets = new Insets(2, 2, 2, 2);
add(panel2, gbc); // add component to the COntentPane
JPanel panel3 = new JPanel();
panel3.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridy = 2;
gbc.weightx = gbc.weighty = 20;
gbc.insets = new Insets(2, 2, 2, 2);
add(panel3, gbc);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // important
pack();
setVisible(true); // important
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() { // important
public void run() {
BorderPanels borderPanels = new BorderPanels();
}
});
}
}
on most cases will be better use another LayoutManager
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
Box content = new Box(BoxLayout.X_AXIS);
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
content.add(P1panel);
content.add(P2panel);
tradeframe.setContentPane(content);
tradeframe.setVisible(true);
Invoke setPreferredSize(new Dimension(int width, int height)); method on your panel objects.
Here is the way to do that :
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutTest
{
public GridBagLayoutTest()
{
JFrame frame = new JFrame("GridBag Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
JPanel leftPanel = new JPanel();
leftPanel.setBackground(Color.WHITE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
container.add(leftPanel, gbc);
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.BLUE);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.fill = GridBagConstraints.BOTH;
container.add(rightPanel, gbc);
frame.setSize(600, 400);
frame.setVisible(true);
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new GridBagLayoutTest();
}
};
SwingUtilities.invokeLater(runnable);
}
}
OUTPUT :
You are using setSize() instead of setPreferredSize(). The difference is somewhat misleading and I would consider it a gotcha in java. Some more information about what the difference between the two can be found here.
The article I link has some other pitfalls/gotchas and a useful read if you are new to Java.