I have 7 JPanel containers in total. I'd like to add a png image that I generate, or buffer it with the help of the button(charger image) in the JPanel(imagePan)
Most of the examples I've seen so far in the Swing Tutorials use ImageIcon
The images generated are at 326X254
How to properly add an image to a panel?
Here you'll find the code generating the window below:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
public class View {
private JFrame frame;
private JPanel globalPan, firstHorisontalPan, secondhorisontalPan,
calibrationPan, imagePan, manipPan, solutionPan; // susp
private JButton raproche, ecarter, sauvgarder, demarrer, stop, charger;
private BorderLayout BorderGlobalePan, BorderSecondPane, BorderManipPane,
BorderFirstHorisontalPan, BorderResolPan, BorderCalibPan,
BorderChargerPan;
private JTextArea console;
private Box calibrationBox, solutionBox;
public void init() {
// declaration de JFrame
frame = new JFrame("Rubi's Cube IHM");
// JPanle
globalPan = new JPanel();
firstHorisontalPan = new JPanel();
secondhorisontalPan = new JPanel();
imagePan = new JPanel();
manipPan = new JPanel();
calibrationPan = new JPanel();
solutionPan = new JPanel();
//
calibrationBox = Box.createVerticalBox();
solutionBox = Box.createVerticalBox();
// borderLayout
BorderGlobalePan = new BorderLayout();
BorderSecondPane = new BorderLayout();
BorderManipPane = new BorderLayout();
BorderFirstHorisontalPan = new BorderLayout();
BorderResolPan = new BorderLayout();
BorderCalibPan =new BorderLayout();
BorderChargerPan = new BorderLayout();
// JButton
raproche = new JButton("raprocher");
ecarter = new JButton("ecarter");
sauvgarder = new JButton("sauvgarder");
demarrer = new JButton("demarrer");
stop = new JButton("stop");
charger = new JButton("charger image");
console = new JTextArea();
//add JPanel names
firstHorisontalPan.setBorder(BorderFactory.createTitledBorder("Etat"));
calibrationPan.setBorder(BorderFactory.createTitledBorder("calibration"));
solutionPan.setBorder(BorderFactory.createTitledBorder("résolution & manipulation"));
imagePan.setBorder(BorderFactory.createTitledBorder("visualisation"));
// definition of JButton size
raproche.setPreferredSize(new Dimension(200, 30));
ecarter.setPreferredSize(new Dimension(200, 30));
sauvgarder.setPreferredSize(new Dimension(200, 30));
demarrer.setPreferredSize(new Dimension(200, 30));
stop.setPreferredSize(new Dimension(200, 30));
charger.setPreferredSize(new Dimension(200, 30));
//definition of JPanel size
globalPan.setPreferredSize(new Dimension(1024, 600));
firstHorisontalPan.setPreferredSize(new Dimension(1024, 130));
secondhorisontalPan.setPreferredSize(new Dimension(1024, 480));
imagePan.setPreferredSize(new Dimension(850, 480));
manipPan.setPreferredSize(new Dimension(150, 480));
calibrationPan.setPreferredSize(new Dimension(200, 200));
solutionPan.setPreferredSize(new Dimension(200, 100));
calibrationBox.setPreferredSize(new Dimension(200, 200));
solutionBox.setPreferredSize(new Dimension(200, 100));
firstHorisontalPan.setLayout(BorderFirstHorisontalPan);
firstHorisontalPan.add(console);
//image
// JPane calibration
calibrationBox.add(Box.createVerticalStrut(10));
calibrationBox.add(raproche);
calibrationBox.add(Box.createVerticalStrut(10));
calibrationBox.add(ecarter);
calibrationBox.add(Box.createVerticalStrut(10));
calibrationBox.add(sauvgarder);
calibrationPan.setLayout(BorderCalibPan);
calibrationPan.add(calibrationBox, BorderLayout.CENTER);
// JPane resolution & manipulation
solutionBox.add(Box.createVerticalStrut(10));
solutionBox.add(demarrer);
solutionBox.add(Box.createVerticalStrut(10));
solutionBox.add(stop);
solutionPan.setLayout(BorderResolPan);
solutionPan.add(solutionBox, BorderLayout.CENTER);
//JPane ManipPane
manipPan.setLayout(BorderManipPane);
manipPan.add(calibrationPan, BorderLayout.NORTH);
BorderManipPane.setVgap(20);
manipPan.add(solutionPan, BorderLayout.CENTER);
//JPane secondPane
secondhorisontalPan.setLayout(BorderSecondPane);
secondhorisontalPan.add(manipPan, BorderLayout.WEST);
BorderSecondPane.setHgap(7);
secondhorisontalPan.add(imagePan, BorderLayout.CENTER);
//JPane GlobalHorisontalPane
globalPan.setLayout(BorderGlobalePan);
globalPan.add(firstHorisontalPan, BorderLayout.NORTH);
BorderGlobalePan.setVgap(10);
globalPan.add(secondhorisontalPan, BorderLayout.CENTER);
//Jpane imagePan
BorderChargerPan.setVgap(10);
imagePan.add(charger);
// window
frame.add(globalPan);
frame.setSize(1024, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setTitle("cubeBerry");
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
IHM
How to proprely add an image to a Jpanel?
Create an ImageIcon.
Add the icon to a JLabel.
Add the label to the JPanel.
Read the section from the Swing tutorial on How to Use Icons for more information and working examples.
Also, from your posted code, get rid of all the setPreferredSize() statements. The layout manager will determine the preferred size of the component. Swing was designed to be used with layout managers. Let the layout manager do its job.
console = new JTextArea();
When creating a JTextArea do something like:
console = new JTextArea(5, 30);
The will suggest the size should be 5 rows and 30 columns. Now the layout manager can calculate a preferred size based on this information.
private BorderLayout BorderGlobalePan, BorderSecondPane, BorderManipPane, ...
Variable names should NOT start with an upper case character. Most of your variable are correct, but not all. Be consistent!!!
frame.setSize(1024, 600);
Don't hard code a size. You don't know what the resolution of my computer is. Instead use the pack() method and let the layout managers do their job.
Related
I need to define a layout for a Jframe Window, as in the picture above.
Below is my approach.
A Picture from my resources folder (/resources/...jpg) embed inside the middle(main).
Top, Bottom, Left and Right divided in four parts, whereas their content is a labeled button stretched, so I can map some methods on it later, that change the picture inside the main container.
I tried to display the picture, but I get the result you see in my screenshot. I can't see it inside my main container and I receive no error message.
I don't know if this is because of my wrong approach of using JFrame.
Below you can see my code, I'd be happy if you could help me solving my wrong design layout pattern too.
MyFrame.java
package ms0.gui;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class MyFrame extends JFrame {
public MyFrame () {
setTitle("This is an example title");
setSize(600,600);
setLocation(750,640);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Main Container
Container mainContainer = this.getContentPane();
mainContainer.setLayout(new BorderLayout(8,6));
mainContainer.setBackground(Color.BLUE);
this.getRootPane().setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.green));
//JButton Positions
JButton topButton = new JButton("Oben");
JButton bottomButton = new JButton("Unten");
JButton leftButton = new JButton("Links");
JButton rightButton = new JButton("Rechts");
//Panel Top
JPanel topPanel = new JPanel();
topPanel.setBorder(new LineBorder(Color.BLACK, 3));
topPanel.setBackground(Color.ORANGE);
topPanel.setLayout(new FlowLayout(5));
topPanel.add(topButton);
mainContainer.add(topPanel, BorderLayout.NORTH);
//Panel Middle
JPanel middlePanel = new JPanel();
middlePanel.setBorder(new LineBorder(Color.black, 3));
middlePanel.setLayout(new FlowLayout(4,4,4));
middlePanel.setBackground(Color.cyan);
//Grid Panel Right
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new FlowLayout(4,4,4));
rightPanel.setBorder(new LineBorder(Color.black, 3));
rightPanel.setBackground(Color.GREEN);
rightPanel.add(rightButton);
//Grid Panel Left
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(4,1,5,5));
gridPanel.setBorder(new LineBorder(Color.black, 3));
gridPanel.setBackground(Color.red);
gridPanel.add(leftButton);
//Center Box
JLabel label = new JLabel("Center Box", SwingConstants.CENTER);
label.setOpaque(true);
label.setBorder(new LineBorder(Color.black,3));
middlePanel.add(gridPanel);
mainContainer.add(label);
mainContainer.add(middlePanel, BorderLayout.WEST);
mainContainer.add(rightPanel, BorderLayout.EAST);
//Panel Bottom
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(3));
bottomPanel.add(bottomButton);
bottomPanel.setBackground(Color.magenta);
bottomPanel.setBorder(new LineBorder(Color.BLUE, 3));
mainContainer.add(bottomPanel, BorderLayout.SOUTH);
//Siegel
String filepath = "/resources/siegel.jpg";
int picWidth = 150;
int picHeight = 150;
ImageIcon image1 = new ImageIcon(getClass().getResource(filepath));
//Image scaledImage = img.getScaledInstance(picWidth, picHeight, Image.SCALE_DEFAULT);
//ImageIcon icon = new ImageIcon(scaledImage);
mainContainer.add(new JButton(image1));
}
}
So, as a very basic example, nothing but BorderLayout
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class MyFrame extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyFrame frame = new MyFrame();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public MyFrame() {
setTitle("This is an example title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(new JButton("Top button (stretched)"), BorderLayout.NORTH);
add(new JButton("Left button (stretched)"), BorderLayout.WEST);
add(new JButton("Right button (stretched)"), BorderLayout.EAST);
add(new JButton("Bottom button (stretched)"), BorderLayout.SOUTH);
JLabel label = new JLabel("Picture");
label.setBorder(new EmptyBorder(100, 100, 100, 100));
add(label);
}
}
Remember, simple is often best.
Now, if you absolutely, positively must have the label/picture in another container, you can simply make use of GridBagLayout, as it will centre the child component(s) by default, for example...
JLabel label = new JLabel("Picture");
label.setBorder(new EmptyBorder(100, 100, 100, 100));
// Automatic center position
JPanel mainPane = new JPanel(new GridBagLayout());
mainPane.add(label);
add(mainPane);
And you don't have to use EmptyBorder. GridBagLayout will allow to supply insets which will do the same thing
I have this simple MigLayout:
The two last components (JScrollPanes) should have the same width. But in fact, if I resize the window, they are randomly jumping. Is it possible to make their width equal? How else can I arrange components to make this look symmetrical?
You need your columns to use the same sizegroup/sg in your column constraints. This way both columns will always have the same width.
Like this:
setLayout(new MigLayout("", "[sizegroup main, grow][sizegroup main,grow]"[][][][grow]"));
See also the MigLayout Cheatsheet about sizegroup.
Most of the time I prefer to use the built-in facilities of java rather than mixing much further complex libraries and dependencies for such simple cases. I think when you can achieve the solution with a trivial effort like this it's not needed to use third party libraries such as MIG. This preference comes from the situation you are in: not so many people work with a purchased tools, so you can not get so many help from the community.
I know this question asks about MigLayout but I preferred to show that there is no need to use that for this simple situation. MIG library is rich and have some useful components which can make your life easier but when it comes to layouts I prefer pure java.
Sampling your layout using pure BorderLayout and GridLayout:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
public class TestMain {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
JFrame f = new JFrame();
f.setBounds(50, 50, 500, 400);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.add(createSpacerPanel(10, 10), BorderLayout.NORTH);
f.add(createSpacerPanel(10, 10), BorderLayout.SOUTH);
f.add(createSpacerPanel(10, 10), BorderLayout.EAST);
f.add(createSpacerPanel(10, 10), BorderLayout.WEST);
f.add(new MainPanel());
f.setVisible(true);
}
private static JPanel createSpacerPanel(int width, int height){
JPanel spacer = new JPanel();
spacer.setPreferredSize(new Dimension(width, height));
return spacer;
}
}
class MainPanel extends JPanel{
public MainPanel() {
init();
}
private void init() {
JPanel northPanel = new JPanel(new BorderLayout(10, 10));
northPanel.setPreferredSize(new Dimension(100, 60));
northPanel.add(new JLabel("Class Expression: "), BorderLayout.NORTH);
JTextArea classExpressionTextArea = new JTextArea();
classExpressionTextArea.setSize(10, 40);
northPanel.add(new JScrollPane(classExpressionTextArea), BorderLayout.CENTER);
JButton calculateButton = new JButton("Calculate");
northPanel.add(calculateButton, BorderLayout.EAST);
JPanel definitionPanel = new JPanel(new BorderLayout(10,10));
definitionPanel.add(new JLabel("Definitions Found: "), BorderLayout.NORTH);
JTextArea definitionsTextArea = new JTextArea();
definitionPanel.add(new JScrollPane(definitionsTextArea), BorderLayout.CENTER);
JPanel signaturePanel = new JPanel(new BorderLayout(10,10));
signaturePanel.add(new JLabel("Target Signature: "), BorderLayout.NORTH);
JTextArea targetTextArea = new JTextArea();
signaturePanel.add(new JScrollPane(targetTextArea), BorderLayout.CENTER);
GridLayout gridLayout = new GridLayout(1,1,10,10);
JPanel centerPanel = new JPanel(gridLayout);
centerPanel.add(definitionPanel);
centerPanel.add(signaturePanel);
setLayout(new BorderLayout(10,10));
add(northPanel, BorderLayout.NORTH);
add(centerPanel, BorderLayout.CENTER);
}
}
And the fully resizable output:
The same can be achieved using GridBagLayout which is similar to MigLayout in the way of thinking about the layout and positioning and spanning components over grid cells.
Hope this would be helpful.
I am creating a GUI with a graphics panel, a command panel and a Command List panel. I've got the command panel where I want it at the bottom of the frame using BorderLayout South but my side panel is just tiny and unreadable.
Ill provide a picture of what I want my frame to look like at the end:
What I currently have:
Could anyone explain why the TitledBorder panel is so small?
My code is below:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class PenDriver {
public static void main(String[] args) {
JFrame frame = new JFrame("Pen Simulator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
penPanel panel = new penPanel();
frame.add(panel);
frame.setVisible(true);
}
}
AND
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
public class penPanel extends JPanel {
private JTextField userCommand;
private JLabel instruction1;
private JButton instruct, clear;
private JLabel cmd1;
public penPanel() {
setLayout(new BorderLayout());
// CREATE THE COMMAND PANEL///////
// Set Layout
JPanel command = new JPanel();
command.setLayout(new BoxLayout(command, BoxLayout.LINE_AXIS));
// Create Label and add to panel
instruction1 = new JLabel("Enter Command:");
// Create Buttons
instruct = new JButton("Execute");
clear = new JButton("Clear Graphics");
// Create Text Field to panel
userCommand = new JTextField(10);
command.add(instruction1);
command.add(Box.createRigidArea(new Dimension(4, 0)));
command.add(userCommand);
command.add(Box.createRigidArea(new Dimension(2, 0)));
command.add(instruct);
command.add(Box.createRigidArea(new Dimension(2, 0)));
command.add(clear);
// COMMAND PANEL FINISHED////////
// CREATE THE COMMAND LIST PANEL//////////
JPanel cmdList = new JPanel();
cmdList.setBorder(BorderFactory.createTitledBorder("Command List:"));
cmdList.setLayout(new BoxLayout(cmdList, BoxLayout.PAGE_AXIS));
cmd1 = new JLabel("UP = up");
cmdList.setSize(new Dimension(50, 400));
cmdList.add(cmd1);
add(command, BorderLayout.SOUTH);
add(cmdList, BorderLayout.EAST);
}
}
Thank you!
EDIT: After some tinkering to this code:
cmdList.setPreferredSize(new Dimension(120, 800));
cmdList.add(cmd1);
add(command, BorderLayout.SOUTH);
command.add(Box.createRigidArea(new Dimension(120, 0)));
add(cmdList, BorderLayout.EAST);
Still not quite what im going for and not sure if it's what I am supposed to do. Should I be altering the driver file rather than the JPanels directly?
Notice how there is still a gap to the right of the "Clear Graphics" Button. Any way to get rid of that?
Could anyone explain why the TitledBorder panel is so small?
The size of the text in the border is not used to determine the size of the component. So the width is determined by the preferred size of the component you add to the panel.
So you need to override the getPreferredSize() method of the panel to return the maximum of the default preferred size calculation or the size of the titled border:
JPanel cmdList = new JPanel()
{
#Override
public Dimension getPreferredSize()
{
Dimension preferredSize = super.getPreferredSize();
Border border = getBorder();
int borderWidth = 0;
if (border instanceof TitledBorder)
{
Insets insets = getInsets();
TitledBorder titledBorder = (TitledBorder)border;
borderWidth = titledBorder.getMinimumSize(this).width + insets.left + insets.right;
}
int preferredWidth = Math.max(preferredSize.width, borderWidth);
return new Dimension(preferredWidth, preferredSize.height);
}
};
Notice how there is still a gap to the right of the "Clear Graphics" Button. Any way to get rid of that?
command.add(Box.createRigidArea(new Dimension(120, 0)));
You just added the rigid area to the command panel so you asked to have the extra 120 pixels at the end.
So I'm trying to set up a Gui in Java which holds a list of checkboxes. What determines the length of the list is the highlighted checkboxes. However, when I add more things to the list the checkboxes just get smaller to fit the panel. I've added a vertical scrollbar, but this just doesn't do anything. Is there something I have to do to stop the GridLayout from resizing what it holds or is it the wrong layout?
package darrt;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class TestForScrollBat {
public static void main(String[] args){
new TestForScrollBat();
}
public TestForScrollBat(){
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(0, 1));
JScrollPane scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(50, 30, 300, 50);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JLabel label = new JLabel(" Soc Categories");
JCheckBox soc1 = new JCheckBox("Blood and Lymphatic System Disorder");
JCheckBox soc2 = new JCheckBox("Cardiac Disorders");
JCheckBox soc3 = new JCheckBox("Congenital, familial and Genetic Disorders");
JButton jbtn = new JButton("Go!");
panel.add(label);
panel.add(soc1);
panel.add(soc2);
panel.add(soc3);
panel.add(jbtn);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
I had it before so that it would add a scroll to this panel, but now it doesn't even do that.. It just creates a new JPanel on the JFrame
Your problem is about the following lines in your code:
scrollPane.setBounds(50, 30, 300, 50);
You should not set static sizes and locations when using layouts. You are telling a specific size and location to the scrollPane while you had add it to the center of the contentPane before. These two are in conflict.
And next problem is about this line:
frame.add(panel);
This line will detach the panel from you JScrollPane and add it directly to the contentPane of the JFrame.
By deleting/commenting these lines, your problem will be solved.
I would like to make a layout using Java Swing which looks like the following drawing.
(source: braun-abstatt.de)
On the left is a JPanel which is drawn through paintComponent() in a way that the graphics automatically scale when the window is resized. (The question isn't about that panel. That one's already done.)
Now I need some buttons (the black boxes, added in Photoshop for the drawing) to the right of the JPanel mentioned before. The height of the reddish areas at the top and bottom, next to which there should be just empty space, is calculated along the lines of CONSTANT_FACTOR * getHeight(). Next to each compartment on the left, there should be a group of buttons, lined up to the center of the respective compartment (see the blue lines).
The JPanel containing the buttons knows about the CONSTANT_FACTOR and the number of compartments, so it should be possible to feed this information into a layout manager.
Which layout manager would I best use to achieve this layout? I've read about all the different layout managers, but I can't quite figure out which one or which combination of them best fits in this case.
For example, by use of a different LayoutManager, a very easy and simple container, takes no more than 15-20 minutes:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class ThinLineFrame {
private JFrame frame = new JFrame();
private JScrollPane scrollPane;
private JPanel panel = new JPanel();
private JPanel panelNorth = new JPanel();
private JPanel panelCenter = new JPanel();
private JPanel panelCenterCh1 = new JPanel();
private JPanel panelCenterCh2 = new JPanel();
private JPanel panelCenterCh3 = new JPanel();
private JPanel panelCenterCh4 = new JPanel();
private JPanel panelCenterCh5 = new JPanel();
private JPanel panelSouth = new JPanel();
public ThinLineFrame() {
panelNorth.setBackground(Color.red.darker());
panelNorth.setPreferredSize(new Dimension(80, 30));
//
panelCenter.setBackground(Color.darkGray);
panelCenter.setLayout(new GridLayout(5, 1, 2, 2));
//
panelCenterCh1.setLayout(new BorderLayout());
JButton panelCenterCh1Button = new JButton();
panelCenterCh1.add(panelCenterCh1Button, BorderLayout.CENTER);
//
JButton panelCenterCh2Button1 = new JButton();
JButton panelCenterCh2Button2 = new JButton();
panelCenterCh2.setLayout(new GridLayout(2, 1, 2, 2));
panelCenterCh2.add(panelCenterCh2Button1);
panelCenterCh2.add(panelCenterCh2Button2);
//
JButton panelCenterCh3Button1 = new JButton();
JButton panelCenterCh3Button2 = new JButton();
panelCenterCh3.setLayout(new GridLayout(2, 1, 2, 2));
panelCenterCh3.add(panelCenterCh3Button1);
panelCenterCh3.add(panelCenterCh3Button2);
//
JButton panelCenterCh4Button1 = new JButton();
JButton panelCenterCh4Button2 = new JButton();
panelCenterCh4.setLayout(new GridLayout(2, 1, 2, 2));
panelCenterCh4.add(panelCenterCh4Button1);
panelCenterCh4.add(panelCenterCh4Button2);
//
panelCenterCh5.setLayout(new BorderLayout());
JButton panelCenterCh5Button = new JButton();
panelCenterCh5.add(panelCenterCh5Button, BorderLayout.CENTER);
//
panelCenter.add(panelCenterCh1);
panelCenter.add(panelCenterCh2);
panelCenter.add(panelCenterCh3);
panelCenter.add(panelCenterCh4);
panelCenter.add(panelCenterCh5);
//
panelSouth.setBackground(Color.red.darker());
panelSouth.setPreferredSize(new Dimension(80, 30));
//
panel.setLayout(new BorderLayout(2, 2));
panel.add(panelNorth, BorderLayout.NORTH);
panel.add(panelCenter, BorderLayout.CENTER);
panel.add(panelSouth, BorderLayout.SOUTH);
//
scrollPane = new JScrollPane(panel);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(80, 600));
frame.setLocation(100, 150);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ThinLineFrame dlg = new ThinLineFrame();
}
});
}
}
You should try looking at MigLayout. It's a super flexible LayoutManager that is also very simple.
The code would look something like:
MigLayout layout = new MigLayout("flowy");
panel.setLayoutManager(layout);
panel.add(button1);
panel.adD(button2);
etc..
Try adding debug, flowy to the constructor to get a visual idea of what is going on.
GBC without an anchor, just with plain vanilla GridBagConstraints and preferred size.
Centered JButton with fixed size:
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainWithFixSize {
public static void main(String[] argv) throws Exception {
JFrame frame = new JFrame();
Container container = frame.getContentPane();
GridBagLayout gbl = new GridBagLayout();
container.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
JButton component = new JButton();
component.setPreferredSize(new Dimension(25, 25));
gbl.setConstraints(component, gbc);
container.add(component);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(40, 90));
frame.pack();
frame.setVisible(true);
}
private MainWithFixSize() {
}
}