I have one frame (600X500), A JPanel (50X100) and another JPanel (200X150) and
I am trying to get the following result:
My code is:
public class BtnsPanel extends JPanel{
public BtnsPanel()
{
setSize(50,100);
setBackground(Color.RED);
}
}
public class DialogPanel extends JPanel{
public DialogPanel() {
setSize(150,150);
setBackground(Color.BLUE);
}
}
public class MainFrame extends JFrame{
public MainFrame()
{
setSize(600,500);
setLayout(new BorderLayout());
add(new BtnsPanel(), BorderLayout.CENTER);
add(new DialogPanel(), BorderLayout.CENTER);
}
public static void main(String[] args){
new MainFrame().setVisible(true);
}
}
Code result:
And that is not the expected result.
Your picture is not to scale, but if you are not trying to reach the exact scale of the dimensions you have provided, I would suggest using GridBagLayout instead of BorderLayout:
public class MainFrame extends JFrame {
private JPanel btnsPanel;
private JPanel dialogPanel;
public MainFrame() {
getContentPane().setBackground(Color.BLUE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setPreferredSize(new Dimension(600,500));
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.2, 0.1, 0.5, 0.2};
gridBagLayout.rowWeights = new double[]{0.3, 0.3, 0.15, 0.25};
getContentPane().setLayout(gridBagLayout);
btnsPanel = new JPanel();
btnsPanel.setBackground(Color.RED);
GridBagConstraints gbc_btnsPanel = new GridBagConstraints();
gbc_btnsPanel.insets = new Insets(0, 0, 5, 5);
gbc_btnsPanel.fill = GridBagConstraints.BOTH;
gbc_btnsPanel.gridx = 0;
gbc_btnsPanel.gridy = 0;
gbc_btnsPanel.gridheight = 2;
getContentPane().add(btnsPanel, gbc_btnsPanel);
dialogPanel = new JPanel();
dialogPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
dialogPanel.setBackground(Color.BLUE);
GridBagConstraints gbc_dialogPanel = new GridBagConstraints();
gbc_dialogPanel.insets = new Insets(0, 0, 0, 5);
gbc_dialogPanel.fill = GridBagConstraints.BOTH;
gbc_dialogPanel.gridx = 2;
gbc_dialogPanel.gridy = 1;
gbc_dialogPanel.gridheight = 2;
getContentPane().add(dialogPanel, gbc_dialogPanel);
pack();
}
}
Code Result:
Using GridbagLayout as proposed by EvT is a good and valid solution.
However, if you want to avoid the complexity of GridBagConstraints you can achieve similar results by wrapping btnsPanel and dialogPanel, each by a JPanel like so:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class MainFrame extends JFrame {
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cPane = getContentPane();
cPane.setBackground(Color.BLUE);
cPane.setLayout(new BorderLayout());
JPanel leftPane = new JPanel();
leftPane.setLayout(new BoxLayout(leftPane, BoxLayout.Y_AXIS));
leftPane.setOpaque(false);
JPanel btnsPanel = new JPanel();
btnsPanel.setBackground(Color.RED);
btnsPanel.setPreferredSize(new Dimension(50,100));
leftPane.add(btnsPanel);
leftPane.add(Box.createVerticalGlue());
cPane.add(leftPane, BorderLayout.LINE_START);
JPanel centerPane = new JPanel(new GridBagLayout());
centerPane.setPreferredSize(new Dimension(500,500));
centerPane.setOpaque(false);
JPanel dialogPanel = new JPanel();
dialogPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
dialogPanel.setBackground(Color.BLUE);
dialogPanel.setPreferredSize(new Dimension(200,150));
centerPane.add(dialogPanel);
cPane.add(centerPane, BorderLayout.CENTER);
pack();
}
public static void main(String[] args){
new MainFrame().setVisible(true);
}
}
Related
when I compile and run my code everything seems to work fine except the JButton does not appear. I'm adding it to a JPanel that is on the frame. I'm new so I might not know what to lookout for here. Thanks!
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class TemperatureConverter extends JFrame{
//declarations
private JLabel celJLabel, farJLabel;
private JTextField celJTextField, farJTextField;
private JSlider sliderJSlider;
private JButton closeButton;
private TitledBorder border;
private JPanel topPanel, bottomPanel;
double celsiusDegrees, farenheitDegrees, sliderValue;
DecimalFormat decimalFormat = new DecimalFormat("#.0");
public TemperatureConverter()
{
createUserInterface();
}
public void createUserInterface()
{
//create the JFrame
Container frame = getContentPane();
frame.setBackground(Color.white);
frame.setLayout(null);
border = new TitledBorder("Convert between C & F");
border.setTitleColor(Color.black);
border.setTitleFont(new Font("Default", Font.ITALIC, 12));
border.setTitleJustification(TitledBorder.LEFT);
border.setTitlePosition(TitledBorder.TOP);
topPanel = new JPanel();
topPanel.setBounds(20,10,360,300);
topPanel.setForeground(Color.black);
topPanel.setBackground(Color.white);
topPanel.setLayout(null);
topPanel.setBorder(border);
frame.add(topPanel);
bottomPanel = new JPanel();
bottomPanel.setBounds(20,310,360,50);
bottomPanel.setForeground(Color.black);
bottomPanel.setBackground(Color.white);
bottomPanel.setLayout(null);
frame.add(bottomPanel);
celJLabel = new JLabel();
celJLabel.setBounds(120, 200, 60, 20);
celJLabel.setBackground(Color.white);
celJLabel.setFont(new Font("Default", Font.PLAIN, 12));
celJLabel.setText("Celcius");
celJLabel.setHorizontalAlignment(JLabel.LEFT);
topPanel.add(celJLabel);
farJLabel = new JLabel();
farJLabel.setBounds(120, 220, 60, 20);
farJLabel.setBackground(Color.white);
farJLabel.setFont(new Font("Default", Font.PLAIN, 12));
farJLabel.setText("Faranheit");
farJLabel.setHorizontalAlignment(JLabel.LEFT);
topPanel.add(farJLabel);
celJTextField = new JTextField();
celJTextField.setBounds(195,200, 50, 15);
celJTextField.setFont(new Font("Default", Font.PLAIN, 12));
celJTextField.setHorizontalAlignment(JTextField.CENTER);
celJTextField.setForeground(Color.black);
celJTextField.setBackground(Color.white);
topPanel.add(celJTextField);
farJTextField = new JTextField();
farJTextField.setBounds(195,225, 50, 15);
farJTextField.setFont(new Font("Default", Font.PLAIN, 12));
farJTextField.setHorizontalAlignment(JTextField.CENTER);
farJTextField.setForeground(Color.black);
farJTextField.setBackground(Color.white);
topPanel.add(farJTextField);
sliderJSlider = new JSlider(JSlider.HORIZONTAL, 0,100,0);
sliderJSlider.setBounds(20, 20, 310, 120);
sliderJSlider.setMajorTickSpacing(10);
sliderJSlider.setMinorTickSpacing(5);
sliderJSlider.setPaintTicks(true);
sliderJSlider.setPaintLabels(true);
sliderJSlider.setForeground(Color.black);
sliderJSlider.setBackground(Color.white);
topPanel.add(sliderJSlider);
sliderJSlider.addChangeListener(
new ChangeListener()
{
public void stateChanged(ChangeEvent event)
{
sliderStateChanged(event);
}
}
);
closeButton = new JButton();
closeButton.setBounds(140, 250, 75, 20);
closeButton.setFont(new Font("Default", Font.PLAIN,12));
closeButton.setText("Close");
closeButton.setForeground(Color.black);
closeButton.setBackground(Color.white);
bottomPanel.add(closeButton);
closeButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
closeActionPerformed(event);
}
}
);
setTitle("Temperature Converter");
setSize(400,400);
setVisible(true);
}
public static void main(String[] args)
{
TemperatureConverter application = new TemperatureConverter();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void sliderStateChanged(ChangeEvent event)
{
farenheitDegrees = sliderJSlider.getValue();
calculateCelsiusTemperature();
}
public void calculateCelsiusTemperature()
{
celsiusDegrees = (farenheitDegrees - 32)*5.0/9.0;
outputTemps();
}
public void outputTemps()
{
celJTextField.setText(decimalFormat.format(celsiusDegrees));
farJTextField.setText(decimalFormat.format(farenheitDegrees));
}
public void closeActionPerformed(ActionEvent event)
{
TemperatureConverter.this.dispose();
}
}
I'd follow the advice from the comments, use a proper layout manager.
The actual fault, is the placement of the close button within the bottom panel.
closeButton.setBounds(140, 250, 75, 20);
This might be a typo or a misunderstanding of the coordinate system, each new panel has its own private system where (0,0) is the top left of at component. The button is at (140, 250), however bottomPanel is only 360 x 50, so it is outside the visible bounds..
Try changing to
closeButton.setBounds(0, 0, 75, 20);
Your first and major mistake is this: topPanel.setLayout(null);. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
The solution is simple: learn about and how to use the layout managers, and then use them. You can find links to the Swing tutorials including those for the layout managers and other Swing resources here: Swing Info
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class TempConverter extends JPanel {
private static final int PREF_W = 400;
private static final int GAP = 5;
private JTextField celJTextField = new JTextField(10);
private JTextField farJTextField = new JTextField(10);
private JSlider sliderJSlider = new JSlider(0, 100, 0);
private JButton closeButton = new JButton("Close");
public TempConverter() {
sliderJSlider.setMajorTickSpacing(10);
sliderJSlider.setMinorTickSpacing(5);
sliderJSlider.setPaintTicks(true);
sliderJSlider.setPaintLabels(true);
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Celcius:"), createGbc(0, 0));
textFieldPanel.add(celJTextField, createGbc(1, 0));
textFieldPanel.add(new JLabel("Faranheit:"), createGbc(0, 1));
textFieldPanel.add(farJTextField, createGbc(1, 1));
JPanel textFieldWrapperPanel = new JPanel(new GridBagLayout());
textFieldWrapperPanel.add(textFieldPanel);
JPanel conversionPanel = new JPanel(new BorderLayout());
conversionPanel.setBorder(BorderFactory.createTitledBorder("Foo"));
conversionPanel.setLayout(new BorderLayout());
conversionPanel.add(sliderJSlider, BorderLayout.PAGE_START);
conversionPanel.add(textFieldWrapperPanel, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
bottomPanel.add(closeButton);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout());
add(conversionPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
return gbc;
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
;
if (isPreferredSizeSet()) {
super.getPreferredSize();
}
int prefW = Math.max(PREF_W, superSize.width);
return new Dimension(prefW, superSize.height);
}
private static void createAndShowGui() {
TempConverter mainPanel = new TempConverter();
JFrame frame = new JFrame("TempConverter");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Now you might say that this looks more complicated, and perhaps it is, but what happens when you want to add another JTextField and JLabel to represent the Kelvin temperature scale? For your GUI, you'll need to resize the GUI and recalculate the position of any component that may be effected by adding the new components. For my GUI, you just need to add a few new lines, and the chance of the changes causing a bug in my code is much smaller than that of your changes. e.g. please note the changes below just require 3 lines of code. Everything else remains the same:
public class TempConverter extends JPanel {
private static final int PREF_W = 400;
private static final int GAP = 5;
private JTextField celJTextField = new JTextField(10);
private JTextField farJTextField = new JTextField(10);
private JTextField KelvinJTextField = new JTextField(10); // !!! Added
private JSlider sliderJSlider = new JSlider(0, 100, 0);
private JButton closeButton = new JButton("Close");
public TempConverter() {
sliderJSlider.setMajorTickSpacing(10);
sliderJSlider.setMinorTickSpacing(5);
sliderJSlider.setPaintTicks(true);
sliderJSlider.setPaintLabels(true);
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Celcius:"), createGbc(0, 0));
textFieldPanel.add(celJTextField, createGbc(1, 0));
textFieldPanel.add(new JLabel("Faranheit:"), createGbc(0, 1));
textFieldPanel.add(farJTextField, createGbc(1, 1));
// !!! added
textFieldPanel.add(new JLabel("Kelvin:"), createGbc(0, 2));
textFieldPanel.add(KelvinJTextField, createGbc(1, 2));
I seem to be having some major issues with JLayeredPane. I have a BorderLayout() pane, and I'd like for the West-side element to contain a few JLayeredPane's on top of each other, so I can switch between them to show the right information.
The west pane should be 200 pixels wide and should be as long as the total window is. In my sample code I have added two layers to the JLayeredPanel, but they don't show up. They should be in the west pane.
Here is my code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
public class Main {
private static JFrame mainFrame = new JFrame();
private static JPanel mainPane = new JPanel();
public Main(){}
public static void initGui(){
JLayeredPane westPanel = new JLayeredPane();
westPanel.setPreferredSize(new Dimension(200,0));
westPanel.setBackground(Color.blue);
JPanel layerOne = new JPanel();
layerOne.add(new JLabel("This is layer 1"));
westPanel.add(layerOne, new Integer(0), 0);
JPanel layerTwo = new JPanel();
layerTwo.add(new JLabel("This si layer 2"));
westPanel.add(layerTwo, new Integer(1), 0);
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.yellow);
JPanel eastPanel = new JPanel();
eastPanel.setPreferredSize(new Dimension(200,0));
eastPanel.setBackground(Color.red);
mainPane = new JPanel(new BorderLayout());
mainPane.add(westPanel, BorderLayout.WEST);
mainPane.add(centerPanel, BorderLayout.CENTER);
mainPane.add(eastPanel, BorderLayout.EAST);
mainFrame = new JFrame("Learning to use JLayeredPane");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setBounds(200, 200, 800, 500);
mainFrame.setContentPane(mainPane);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
initGui();
}
}
What this results in:
JLayeredPane uses a null layout and so you are responsible for stating the size and location of all components added to it. If not they will default to a location of [0, 0] and a size of [0, 0].
try this, its working
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
public class Main {
private static JFrame mainFrame = new JFrame();
private static JPanel mainPane = new JPanel();
public Main(){}
public static void initGui(){
JLayeredPane westPanel = new JLayeredPane();
westPanel.setLayout(null);
westPanel.setPreferredSize(new Dimension(200,0));
westPanel.setBackground(Color.blue);
JPanel layerOne = new JPanel();
layerOne.add(new JLabel("This is layer 1"));
layerOne.setBounds(0, 0, 100, 100);
westPanel.add(layerOne, new Integer(0), 0);
JPanel layerTwo = new JPanel();
layerTwo.add(new JLabel("This si layer 2"));
layerTwo.setBounds(0, 100, 100, 100);
westPanel.add(layerTwo, new Integer(1), 0);
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.yellow);
JPanel eastPanel = new JPanel();
eastPanel.setPreferredSize(new Dimension(200,0));
eastPanel.setBackground(Color.red);
mainPane = new JPanel();
mainPane.setLayout(new BorderLayout());
mainPane.add(westPanel, BorderLayout.WEST);
mainPane.add(centerPanel, BorderLayout.CENTER);
mainPane.add(eastPanel, BorderLayout.EAST);
mainFrame = new JFrame("Learning to use JLayeredPane");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setBounds(200, 200, 800, 500);
mainFrame.setContentPane(mainPane);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
initGui();
}
}
How can I position my labels with this code? It seems that gridbaglayout is not working here, especially the gridbagconstraints. Even if I change the gridx and gridy values, the labels are not moving.
I need to make it in like 3 even columns, 1 column = 1 panel
package nest;
import javax.swing.*;
import java.awt.*;
public class nested extends JFrame{
public static void main(String[] args) {
JFrame f=new JFrame("Bio Data");
JPanel p1=new JPanel(new GridBagLayout());
JPanel p2=new JPanel(new GridBagLayout());
//JPanel p3=new JPanel(new GridBagLayout());
GridBagConstraints c1=new GridBagConstraints();
GridBagConstraints c2=new GridBagConstraints();
JLabel l1=new JLabel("aa");
JLabel l2=new JLabel("bb");
c1.gridx=1;
c1.gridy=1;
p1.add(l1, c1);
c2.gridx=4;
c2.gridy=4;
p2.add(l2, c2);
f.add(p1);
f.add(p2);
f.setVisible(true);
f.setSize(800,500);
f.setResizable(false);
f.setLayout(new FlowLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Changing gridx and gridy does not change the actual position of the labels, but rather the order/format that the labels will be displayed in. If you have something in gridx 4 but nothing in gridx 1,2 or 3 then that object will be the first column.
Also, it woulld be very odd to put a new panel in each column since you can put things in different rows of the gridBagLayout. Here is a short example of a gridBagLayout inside a flowLayout with three different columns of labels:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import java.awt.Insets;
public class nest extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
nest frame = new nest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public nest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(0, 1, 0, 0));
JPanel panel = new JPanel();
contentPane.add(panel);
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JPanel panel_1 = new JPanel();
panel.add(panel_1);
GridBagLayout gbl_panel_1 = new GridBagLayout();
gbl_panel_1.columnWidths = new int[]{0, 0, 27, 0};
gbl_panel_1.rowHeights = new int[]{0, 16, 0};
gbl_panel_1.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panel_1.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panel_1.setLayout(gbl_panel_1);
JLabel lblNewLabel_1 = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1.gridx = 0;
gbc_lblNewLabel_1.gridy = 0;
panel_1.add(lblNewLabel_1, gbc_lblNewLabel_1);
JLabel lblNewLabel = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 0;
panel_1.add(lblNewLabel, gbc_lblNewLabel);
JLabel lblNewLabel_2 = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel_2.gridx = 2;
gbc_lblNewLabel_2.gridy = 0;
panel_1.add(lblNewLabel_2, gbc_lblNewLabel_2);
JLabel lblLabel = new JLabel("New label");
GridBagConstraints gbc_lblLabel = new GridBagConstraints();
gbc_lblLabel.gridx = 2;
gbc_lblLabel.gridy = 1;
panel_1.add(lblLabel, gbc_lblLabel);
}
}
I created this with the Google WindowBuilder. Note that you don't necessarily need to set the columnWidths, rowHeights, columnWeights, or rowWeights (and it is better not to sometimes when you have dynamic content). Hopefully this helps.
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;
}
}
}
I cant transfer any of the relatet posts to my simple problem.
In order to get into GridBagLayout i wrote a simple example:
JFrame frame = new JFrame();
JPanel main =new JPanel();
frame.setContentPane(main);
GridBagLayout gbl=new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
main.setLayout(gbl);
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
gbc.gridx=0;
gbc.gridy=0;
gbc.gridheight=1;
gbc.gridwidth=1;
gbc.fill=GridBagConstraints.WEST;
gbl.setConstraints(btn1, gbc);
gbc.gridx=0;
gbc.gridy=1;
gbl.setConstraints(btn2, gbc);
frame.setSize(new Dimension(200,100));
main.add(btn1);
main.add(btn2);
frame.setVisible(true);
Here i have the Problem that neither .fill nor any other parameter of GBConstrains sems to work. I ever get the two buttons in the middle of the window.
thx in advance
Your configuration of your GridBagConstraint are incorrect:
fill can only take: NONE, VERTICAL, HORIZONTAL or BOTH.
anchor can use relative location within a "cell"
fill and anchor almost always require to use weightx/weighty
Try to avoid using gridx and gridy because they get hard to maintain. Instead use their default value (RELATIVE) and you can change the value of gridwidth/gridheight to set it to 1 (or more if needed) and REMAINDER to make the layout wrap to next line/column (components are then positionned in the order they were added to the container.
Here is a working code of yours (although I am not sure of the exact layout you were targetting):
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestGBL {
protected void initUI() {
JFrame frame = new JFrame();
GridBagLayout gbl = new GridBagLayout();
JPanel main = new JPanel(gbl);
frame.setContentPane(main);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1.0;
main.setLayout(gbl);
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
gbl.setConstraints(btn1, gbc);
gbl.setConstraints(btn2, gbc);
main.add(btn1);
main.add(btn2);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestGBL().initUI();
}
});
}
}
Edit: I made a sample application that demonstrates how to use GridBadLayout that is reusing the constraints:
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test1 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test1 window = new Test1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
JButton btnTest = new JButton("Test1");
GridBagConstraints gbc_btnTest = new GridBagConstraints();
gbc_btnTest.insets = new Insets(0, 0, 0, 5);
gbc_btnTest.gridx = 0;
gbc_btnTest.gridy = 0;
frame.getContentPane().add(btnTest, gbc_btnTest);
JButton btnTest_1 = new JButton("Test2");
gbc_btnTest.gridx = 1;
gbc_btnTest.gridy = 0;
frame.getContentPane().add(btnTest_1, gbc_btnTest);
}
}