Having trouble getting the swing layout to work as I want. - java

I have a simple GUI and I just want to have some text fields stacked on top of each other, with each box being a JPanel. I'm currently using FlowLayout for both the JFrame and JPanel but it changes from being stacked to being in a row when I maximize. Ideally I'd like the text fields to stay in the center of the window even if its maximized. I was looking at using a BoxLayout but was having some trouble getting that to work.
public static Component textbox(String x){
JPanel panel = new JPanel(new FlowLayout(5,5,5));
JLabel lbltAm= new JLabel(x);
JTextField tftAm = new JTextField(10);
lbltAm.setFont(new Font("Serif", Font.PLAIN, 14));
lbltAm.setForeground(Color.white);
panel.add(lbltAm, BorderLayout.NORTH);
panel.add(tftAm, BorderLayout.CENTER);
panel.setBackground(Color.DARK_GRAY);
Border lowerbevel = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
panel.setBorder(lowerbevel);
return panel;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Tip Calculator");
//Add Textbox
frame.setLayout(new BoxLayout(frame, BoxLayout.Y_AXIS));
String Label = "Tip Calculator";
JLabel header = new JLabel(Label);
header.setFont(new Font("Serif", Font.BOLD, 18));
frame.add(header);
frame.add(textbox("Total"));
frame.add(textbox("Tip %"));
frame.add(textbox("People"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.gray);
frame.setPreferredSize(new Dimension(300, 400));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

It's a matter of opinion, but for flexibility, I prefer to use GridBagLayout
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
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 TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(textbox("Total"), gbc);
add(textbox("Tip %"), gbc);
add(textbox("People"), gbc);
}
public Component textbox(String x) {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(5, 5, 5, 5);
JLabel lbltAm = new JLabel(x);
JTextField tftAm = new JTextField(10);
lbltAm.setFont(new Font("Serif", Font.PLAIN, 14));
lbltAm.setForeground(Color.white);
panel.add(lbltAm, gbc);
panel.add(tftAm, gbc);
panel.setBackground(Color.DARK_GRAY);
Border lowerbevel = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
panel.setBorder(lowerbevel);
return panel;
}
}
}
Or if your wanted the "boxes" to occupy the whole area when expanded, you could use something like...
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(textbox("Total"), gbc);
add(textbox("Tip %"), gbc);
add(textbox("People"), gbc);
Which results in something like...
Have a look at Laying Out Components Within a Container and How to Use GridBagLayout for more details

Firstly, I don't know why you're adding components to the JPanel with a method that is for BorderLayout after you've set the layout of panel as FlowLayout.
If you want to keep the components centered at all times (even if the screen is maximized), FlowLayout is probably not the best option for you to work with, as FlowLayout continues to position components horizontally until they fill the width of the frame (one row) and then, it begins the next row. Therefore, if the screen size is maximized, there will be more components per row and they won't be stacked. I would suggest using a GridLayout with one column like so:
frame.setLayout(new GridLayout(3 *(number of rows/components)*, 1));
You can do the same with the JPanel. After that, set the horizontal alignment of each component as centered like so:
component.setHorizontalAlignment(componentName.CENTER);
Hope this helps!

Try to use GridLayout instead of BoxLayout in createAndShowGUI.
frame.setLayout(new GridLayout(4,1));

Related

How to get 2 JPanels within 1 JPanel, resizable, with fixed proportion?

Let's say a JFrame contains just 1 JPanel. This JPanel is divided into 2 JPanels occupying accordingly 0.75 and 0.25 of the JFrame height. I want all of this to be resizable along with the window size.
I have no idea how to do this in Java.
I'm a newbie to Java. I've read a bit about layouts, but all I can see is how to set preferred size in constructor (ceasing to resize when this number is reached) or some fixed sizes obtained through setting borders.
JFrame with a BorderLayout, onto that, add a JPanel with a GridBagLayout. Add your other two panels onto this.
See Laying Out Components Within a Container and How to Use GridBagLayout for more details
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
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 TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 0.75;
JPanel top = new JPanel(new GridBagLayout());
top.add(new JLabel("Top"));
top.setBackground(Color.RED);
add(top, gbc);
gbc.gridy++;
gbc.weighty = 0.25;
JPanel bottom = new JPanel(new GridBagLayout());
bottom.add(new JLabel("Bottom"));
bottom.setBackground(Color.BLUE);
add(bottom, gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}

Positioning elements in a JPanel of CardLayout

I'm having trouble positioning elements in a JPanel. I tried using GridBagLayout but that doesn't seem to make any of the parts of the panel GUI components move. What should I do?
panel.add(Label);
panel.add(TextField);
panel.add(Label);
panel.add(JChooser);
Nothing seems to help move these GUI elements. They just act like they are in a FlowLayout. What should I do? I'm using a CardLayout for another panel (that panel holds other panels like this one in it), but this panel, I need to align them to the left.
The Label and TextField need to be on the same line, but the Label and JChooser need to be on a different line.
Example:
SomeLabel : [ TextField ]
SomeLabel : [Chooser]
I hope I explained well enough.
Take a closer look at Laying Out Components Within a Container and How to Use GridBagLayout
GridBagLayout requires constraints, which define how and where a component will be positioned within the virtual grid maintained by it
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout {
public static void main(String[] args) {
new TestLayout();
}
public TestLayout() {
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 TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(4, 4, 4, 4);
add(new JLabel("SomeLabel :"), gbc);
gbc.gridy++;
add(new JLabel("SomeLabel :"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.BOTH;
add(new JTextField(10), gbc);
gbc.gridy++;
add(new JComboBox(new Object[]{"Puppies", "Kittens"}), gbc);
}
}
}
To set elements in JPanel use one of LayoutManagers.
If you want to set components free from location.
then use following to remove layout.
panel.setLayout(null);
After this you can call setBounds method to set bounds for component, or setLocation .
comp.setLocation(int left, int top);
comp.setBounds(int left, int top, int width, int height);

GUI: JButton Covering almost the entire screen

I have encountered a problem whilst working the JFrame's, and JButtons. I am trying to center my JButton, however when I do so, it covers almost the entire screen. Any idea's on what's causing this?
Here is a picture on how it looks :
And here is my code :
package character;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
/**
* Created by Niknea on 6/28/14.
*/
public class characterSelector{
JFrame cselectorButtons, clogo;
JLabel logo, characterName, label;
JButton male, female;
public characterSelector(){
this.createCharacterSelector();
}
public void createCharacterSelector() {
try {
label = new JLabel(new ImageIcon(ImageIO.read(getClass()
.getResource("/resources/Grass_Background.jpg"))));
cselectorButtons = new JFrame("SupremeSoccer");
logo = new JLabel(new ImageIcon(ImageIO.read(this.getClass().getResource("/resources/Character_Selector_Image.png"))));
characterName = new JLabel("<Character Name>");
characterName.setFont(new Font(characterName.getFont().getName(),
Font.HANGING_BASELINE, 50));
/*
Buttons
*/
male = new JButton("Male");
////******************////
//// END OF BUTTONS ////
////****************////
cselectorButtons.add(logo);
cselectorButtons.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cselectorButtons.setContentPane(label);
cselectorButtons.setLayout(new BorderLayout());
cselectorButtons.add(logo, BorderLayout.NORTH);
cselectorButtons.add(male, BorderLayout.CENTER);
cselectorButtons.pack();
cselectorButtons.setLocationRelativeTo(null);
cselectorButtons.setVisible(true);
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
Thanks again.
Any idea's on what's causing this?
This is the default behaviour of BorderLayout. The component at the CENTER position will occupy the maximum amount of space the is available from the parent component, when the other (NORTH, SOUTH, EAST, WEST) positions have been taken into account
Depending on what you are trying to achieve you might consider creating another JPanel (set it's opaque state to false so it's transparent) and use something like GridLayout or GridBagLayout instead.
Take a look at A Visual Guide to Layout Managers for some more ideas
Updated
So based on your linked code, I changed
part2 = new JPanel();
to
part2 = new JPanel(new java.awt.GridBagLayout());
And got...
Updated with additional example
Start by breaking down your requirements into individual containers and focus on the layout requirements for each individual, then build them all back into a single container.
This will make changing them later much easier and also make controlling them much easier...
import java.awt.BorderLayout;
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 java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ExampleLayout {
public static void main(String[] args) {
new ExampleLayout();
}
public ExampleLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private HeaderPane header;
private ScorePane score;
private CharacterSelectionPane characterSelection;
public TestPane() {
setLayout(new BorderLayout());
JLabel background = new JLabel();
try {
BufferedImage img = ImageIO.read(getClass().getResource("/Grass.jpg"));
background.setIcon(new ImageIcon(img));
} catch (IOException ex) {
ex.printStackTrace();
}
add(background);
background.setLayout(new GridBagLayout());
header = new HeaderPane();
score = new ScorePane();
characterSelection = new CharacterSelectionPane();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
background.add(header, gbc);
background.add(score, gbc);
gbc.weighty = 1;
background.add(characterSelection, gbc);
}
}
public class HeaderPane extends JPanel {
public HeaderPane() {
setLayout(new BorderLayout());
JLabel label = new JLabel("Character Selection");
label.setForeground(Color.WHITE);
label.setFont(label.getFont().deriveFont(Font.BOLD, 48f));
label.setHorizontalAlignment(JLabel.CENTER);
add(label);
setOpaque(false);
}
}
public class ScorePane extends JPanel {
public ScorePane() {
JLabel label = new JLabel("[-][-[]-][-]");
label.setForeground(Color.YELLOW);
add(label);
setOpaque(false);
}
}
public class CharacterSelectionPane extends JPanel {
private JButton btMale;
private JButton btFemale;
private JTextField tfName;
private JButton btContinue;
public CharacterSelectionPane() {
setOpaque(false);
setLayout(new GridBagLayout());
btMale = new JButton("Male");
btFemale = new JButton("Female");
btContinue = new JButton("Continue");
tfName = new JTextField(10);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.fill = GridBagConstraints.HORIZONTAL;
add(btMale, gbc);
gbc.gridx++;
add(btFemale, gbc);
gbc.gridx = 0;
gbc.gridy++;
add(new JLabel("Name:"), gbc);
gbc.gridx++;
add(tfName, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(btContinue, gbc);
}
}
}
Use a BoxLayout or (easier) GridBagLayout for the bottom area, as seen in this answer.

Align components on the page top right with GridBagLayout Manager

i am trying to make a login page just like facebook, but the code i have written is not showing it on the top left side instead it is showing at the centre of page, i am using GridBagLayout and anchore for setting text at the FIRST_LINE_END.
final JFrame f2=new JFrame("Admin Main");
f2.setSize(1350,730);
f2.setVisible(true);
f1.setVisible(false);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);![enter image description here][2]
GridBagLayout gbl=new GridBagLayout();
final JPanel p2=new JPanel(gbl){
private Image img = ImageIO.read(new File("F:\\Untitled Folder\\Rohan\\football2.jpg"));
#Override
protected void paintComponent( Graphics g ) {
super.paintComponent(g);
g.drawImage(img, 0,0,1366,730, null);
}
};;
GridBagConstraints g2=new GridBagConstraints();
g2.insets=new Insets(3,3,3,3);
JLabel l2=new JLabel("Admin ID",JLabel.LEFT);
JLabel l3=new JLabel("Password",JLabel.LEFT);
l2.setFont(new Font("TimesRoman",Font.BOLD,16));
l2.setForeground(Color.BLUE);
l2.setBackground(Color.WHITE);
l3.setFont(new Font("TimesRoman",Font.BOLD,16));
l3.setForeground(Color.BLUE);
l3.setBackground(Color.WHITE);
final JTextField t1=new JTextField(15);
final JPasswordField pw1=new JPasswordField(15);
JButton b3=new JButton("Back");
JButton b4=new JButton("Sign in");
f2.add(p2);
g2.anchor=GridBagConstraints.FIRST_LINE_END;
g2.gridx=1;
g2.gridy=1;
p2.add(l2,g2);
g2.gridx=2;
g2.gridy=1;
p2.add(t1,g2);
g2.gridx=1;
g2.gridy=2;
p2.add(l3,g2);
g2.gridx=2;
g2.gridy=2;
p2.add(pw1,g2);
g2.gridx=1;
g2.gridy=3;
p2.add(b3,g2);
g2.gridx=2;
g2.gridy=3;
p2.add(b4,g2);
I see two problems in your current layout:
You put your login panel in the center of the parent BorderLayout (so your panel gets stretched to the size of its container)
You have nothing in your GridBagLayout that will "push" your components to the top and to the left.
There are several options here:
You nest your login panel into several panels (for example using BorderLayout, once with the constraint NORTH and the second time with the constraint WEST).
Add your loginPanel to the WEST and you add a "filler" component to the bottom of the GridBagLayout in order to push the other components to the top.
Here is a demo of the second solution:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
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.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestLoginGridBagLayout {
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame("Admin Main");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel background = new JLabel(new ImageIcon(new URL(
"http://media1.santabanta.com/full1/Football/Football%20Abstract/football-abstract-6a.jpg"))) {
#Override
public Dimension getPreferredSize() {
Dimension preferredSize = super.getPreferredSize();
Dimension layoutPreferredSize = super.preferredSize();
preferredSize.width = Math.max(preferredSize.width, layoutPreferredSize.width);
preferredSize.height = Math.max(preferredSize.height, layoutPreferredSize.height);
return preferredSize;
}
};
background.setLayout(new BorderLayout());
frame.add(background);
GridBagLayout gbl = new GridBagLayout();
final JPanel loginPanel = new JPanel(gbl);
loginPanel.setOpaque(false);
background.add(loginPanel, BorderLayout.WEST);
JLabel adminIDLabel = new JLabel("Admin ID", JLabel.LEFT);
JLabel passwordLabel = new JLabel("Password", JLabel.LEFT);
adminIDLabel.setFont(new Font("TimesRoman", Font.BOLD, 16));
adminIDLabel.setForeground(Color.BLUE);
adminIDLabel.setBackground(Color.WHITE);
passwordLabel.setFont(new Font("TimesRoman", Font.BOLD, 16));
passwordLabel.setForeground(Color.BLUE);
passwordLabel.setBackground(Color.WHITE);
final JTextField adminID = new JTextField(15);
final JPasswordField password = new JPasswordField(15);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
buttonPanel.setOpaque(false);
JButton back = new JButton("Back");
JButton signIn = new JButton("Sign in");
buttonPanel.add(back);
buttonPanel.add(signIn);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(3, 3, 3, 3);
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
loginPanel.add(adminIDLabel, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
loginPanel.add(adminID, gbc);
gbc.gridwidth = 1;
loginPanel.add(passwordLabel, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
loginPanel.add(password, gbc);
loginPanel.add(buttonPanel, gbc);
GridBagConstraints gbcFiller = new GridBagConstraints();
gbcFiller.weightx = 1.0;
gbcFiller.weighty = 1.0;
gbcFiller.fill = GridBagConstraints.BOTH;
loginPanel.add(Box.createGlue(), gbcFiller);
frame.pack();
frame.setVisible(true);
}
/**
* #param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestLoginGridBagLayout().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
}
I also took the liberty of:
Rename your variables to meaningful names (it makes your code easier to read for others)
Replace your custom background image panel with a JLabel
Move your buttons to a nested panel with another LayoutManager
Take another background image since I don't have yours.
If you want it explicitly to be in the top left I'd rather use the NORTHWEST anchor. FIRST_LINE_END for text flowing left to right would also put the text on the right corner and the other way around for right to left.
Also, switch gridx and gridy to start at 0 instead of 1. And increment from as needed from there.
So for example:
g2.anchor=GridBagConstraints.NORTHWEST;
g2.gridx=0;
g2.gridy=0;
p2.add(l2,g2);
g2.gridx=1;
g2.gridy=0;
p2.add(t1,g2);
/*And so on for the rest of the block*/
Use FIRST_LINE_START as anchor value.
g2.anchor=GridBagConstraints.FIRST_LINE_START;

Working with nested Panels

Trying to build out a GUI for my game but no matter what layout I work with I can't get the nest of panels to do what I like
My goal is this
http://i182.photobucket.com/albums/x202/NekoLLX/CharGenmockup-1.jpg
http://i182.photobucket.com/albums/x202/NekoLLX/CharGenmockup2.jpg
And Building off the Mad ones excelent revision I've got my left side as i like it but now the right eludes me
The general idea is that clicking on the title bars of the left menu will colapase (set visible to false) the content panes associated with them
//http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html
//http://stackoverflow.com/questions/16430922/working-with-nested-panels
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.*;
public class JaGCharCreation {
//set inital size of window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int initalWidth = (int) screenSize.width - 50;
int initalHeight = (int) screenSize.height - 50;
public static void main(String[] args) {
new JaGCharCreation ();
}
//set up thread safe invoking for GUI
public JaGCharCreation () {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
//frame.setLocationRelativeTo(null);
frame.setVisible(true);
// Give the frame an initial size.
frame.setSize(initalWidth, initalHeight);
}
});
}
//main panel to hold all others
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(0, 2));
add(createLeftPane());
add(createRightPane());
}//end of class for master frame
protected JPanel createLeftPane() {
JLabel CharName = new JLabel("Character Name");
CharName.setFont(new Font("Impact", Font.BOLD, 30));
CharName.setBorder(new EmptyBorder(0, 81,0, 00));
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.setBackground(Color.RED);
JPanel content = new JPanel(new GridBagLayout());
content.setOpaque(false);
JPanel view3D = new JPanel();
view3D.setBackground(Color.DARK_GRAY);
JPanel view2D = new JPanel();
view2D.setBackground(Color.PINK);
JPanel viewIsometric = new JPanel();
viewIsometric.setBackground(Color.YELLOW);
JPanel viewData = new JPanel();
viewData.setBackground(Color.MAGENTA);
JPanel top = new JPanel(new GridLayout(0, 2));
top.setBorder(new EmptyBorder(0, 80,0, 80));
top.setBackground(Color.GREEN);
top.add(view3D);
top.add(view2D);
JPanel bottom = new JPanel(new GridLayout(2, 0));
bottom.setBorder(new EmptyBorder(0, 80,0, 80));
bottom.setBackground(Color.GREEN);
bottom.add(viewIsometric);
bottom.add(new JScrollPane(viewData));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weighty = 0.5f;
gbc.weightx = 1f;
gbc.fill = GridBagConstraints.BOTH;
content.add(top, gbc);
content.add(bottom, gbc);
panel.add(content);
panel.add(CharName, BorderLayout.NORTH);
return panel;
}//end left pane
protected JPanel createRightPane() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(Color.BLUE);
//set up our image for the title bars
ImageIcon icon = new ImageIcon("GradientDetail.png");
Image img = icon.getImage();
img = img.getScaledInstance(initalWidth/2, 40, java.awt.Image.SCALE_SMOOTH);
final ImageIcon iconSM = new ImageIcon(img);
JPanel name_panel = new JPanel(new BorderLayout())
{
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(iconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
name_panel.setOpaque( false );
JLabel label = new JLabel(" Character Name");
label.setFont(new Font("Impact", Font.BOLD, 30));
label.setForeground(Color.white);
label.setOpaque(false);
JPanel name_panel_text = new JPanel(new BorderLayout());
name_panel_text.setBackground(Color.WHITE);
name_panel.add(label, BorderLayout.NORTH);
panel.add(name_panel_text);
panel.add(name_panel);
return panel;
}//end right pane
//bassed from http://stackoverflow.com/questions/7340001/determine-clicked-jpanel-component-in-the-mouselistener-event-handling
public class MouseAdapterMod extends MouseAdapter {
// usually better off with mousePressed rather than clicked
public void mousePressed(MouseEvent e) {
if (e.getSource() == "name_panel"){
}
}
}
}//end master panel set
}//end master class
Something along the lines of ...
To be honest, I tried following your code, but got lost, so I re-wrote it...
Basically, you relying on setSize which is going to be ignored and changed by the layout managers as they see fit.
This example uses GridBagLayout and weighty to adjust the space allocated to the top (2D/3D) views and the bottom views, but you should also take a look at overriding the getPreferredSize of the final components, to provide better hints to the layout managers.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
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) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(0, 2));
add(createLeftPane());
add(createRightPane());
}
protected JPanel createLeftPane() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.setBackground(Color.RED);
JPanel content = new JPanel(new GridBagLayout());
content.setOpaque(false);
JPanel view3D = new JPanel();
view3D.setBackground(Color.DARK_GRAY);
JPanel view2D = new JPanel();
view2D.setBackground(Color.PINK);
JPanel viewIsometric = new JPanel();
viewIsometric.setBackground(Color.YELLOW);
JPanel viewData = new JPanel();
viewData.setBackground(Color.MAGENTA);
JPanel top = new JPanel(new GridLayout(0, 2));
top.setBorder(new LineBorder(Color.GREEN, 2));
top.add(view3D);
top.add(view2D);
JPanel bottom = new JPanel(new GridLayout(2, 0));
bottom.add(viewIsometric);
bottom.add(new JScrollPane(viewData));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weighty = 0.5f;
gbc.weightx = 1f;
gbc.fill = GridBagConstraints.BOTH;
content.add(top, gbc);
content.add(bottom, gbc);
panel.add(content);
panel.add(new JLabel("Character name"), BorderLayout.NORTH);
return panel;
}
protected JPanel createRightPane() {
JPanel panel = new JPanel();
panel.setBackground(Color.BLUE);
return panel;
}
}
}

Categories

Resources