Need help using GridBagLayout - java

I want to make the password label and text field below the ID..but i`m kind of new to GriBagLayout.
I hope you can help me.
Here is my code:
class LoginPanel extends JPanel {//login components
private JButton exitbtn = new JButton("Exit");
private JLabel idLabel = new JLabel("Staff ID : ");
private JTextField idJtf = new JTextField(10);
private JLabel pwLabel = new JLabel("Password : ");
private JPasswordField pwJtf = new JPasswordField(10);
LoginPanel() {
setOpaque(false);
setLayout(new GridBagLayout());
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
//add(new JLabel("Staff ID: ")); add(new JTextField(10));
//add(new JLabel("Password: ")); add(new JPasswordField(10));
add(idLabel);
add(idJtf);
add(pwLabel);
add(pwJtf);
//add(exitbtn);
}
}

It is as simple as just reading this tutorial: GridBagLayout

If you are familiar with creating HTML pages using tables, GridBagLayout should be easy for you
Placing controls one below the other is like placing them to a table with single column. It means that you need to set 0 as a column number and [0..3] as row numbers:
GridBagConstraints c = new GridBagConstraints();
int rowNum = 0
c.gridx = 0;
c.gridy = rowNum;
add(idLabel, c);
c.gridy++;
add(idJtf, c);
c.gridy++;
add(pwLabel, c);
c.gridy++;
add(pwJtf, c);
However for such simple layout you can use another layout managers

Do yourself a favor and stop using GridBagLayout. GridBagLayout is a layoutmanager from a previous era. I'll realize it is in all the "official" Oracle Java docs but most people avoid it now a days (and for good reasons). A good alternative for complex layouts GridBag is meant to tackle is Jgoodies FormLayout ( http://www.jgoodies.com/freeware/libraries/forms/ ). I'll guarantee you that you will maintain your sanity and your life's quality will improve measurably :-)

Related

I cant align this to right part of my Jpanel

I am trying to align all the buttons on the left all on top of each other, but whatever i do it always seems to stay in the center, i have tryed "c.anchor = GridBagConstraints.EAST;" but that didn't help and now im stuck please help.
JButton Button1 = new JButton("<html> Li <center> <small> 7 <br> 3<small/> <center/> <html/> ");
JButton Button2 = new JButton("<html> Na <center> <small> 32<br> 11<small/> <center/> <html/> ");
JButton Button3 = new JButton("<html>K<center><small> 39 <br> 19<small/> <center/> <html/> ");
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();
Button1.setPreferredSize(new Dimension(50, 50));
Button2.setPreferredSize(new Dimension(50, 50));
Button3.setPreferredSize(new Dimension(50, 50));
GridBagLayout layout = new GridBagLayout() ;
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.anchor = GridBagConstraints.EAST;
setLayout(layout);
add(Button1, c);
add(Button2, c);
add(Button3, c);
add(exit);
setSize(width, height);
setExtendedState(JFrame.MAXIMIZED_BOTH);
//TODO Align to left
setUndecorated(true);
setLocationRelativeTo(null);
c.gridx = 0;
c.anchor = GridBagConstraints.EAST;
setLayout(layout);
add(Button1, c);
add(Button2, c);
add(Button3, c);
add(exit);
Well for one thing you are adding all the components to the same cell since you use the same constraints. If you want them on different rows then you need to specify the a different "gridy" value for each component.
it always seems to stay in the center,
This is the default behaviour unless you specify a weightx/weighty value.
The easier way would be to use a JPanel with a GridLayout. The add all the button to the panel. Finally you add the panel to the frame using:
frame.add(buttonPanel, BorderLayout.LINE_START);
I suggest you start by reading the section from the Swing tutorial on Layout Managers. There are working examples of all the layout managers mentioned above.
Other problems:
Variable names should not start with an upper case character.
Don't use setPreferredSize() on a component. Each component should determined its own preferred size. The layout manager will then use this information.
The GUI code should execute on the Event Dispatch Thread (EDT).
The Swing tutorials all follow the above standards, so download the demo code to learn from that.

how to have 2 lists of componmets on a panel [duplicate]

This question already has an answer here:
JPanel & components change position automatically
(1 answer)
Closed 8 years ago.
I want to have a list of text fields and labels aligned vertically on a panel with each label corresponding to the appropriate text field and appearing beside it on the UI. The value in the text field will be later called for another function.
The problem is that I can't seem to get the layout right. I have tried using Spring Layout but I can't get my head around it......Basically can I do this any other way? I'm currently using box layout for the panel but it only shows up a list of text fields with a list of labels underneath it. I'm still a noob and I really need some fresh input on this. Any help would be very much appreciated, thanks.
You could simply use GridBagLayout (although MigLayout might worth a look as well)...
setLayout(new GridLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
for (int index = 0; index < 10; index++) {
gbc.anchor = GridBagConstraints .EAST;
gbc.gridx = 0;
add(new JLabel("Label " + index), gbc);
gbc.anchor = GridBagConstraints .WEST;
gbc.gridx++;
add(new JTextField(10), gbc);
gbc.gridy++;
}
Now, obviously, this is just an example used to demonstrate the concept, you'll need to expand the idea and apply it to your particular problem...
Take a look at How to use GridBagLayout for more detaols
I would suggest to have a look at RiverLayout manager. It is really simple and straightforward to use.
http://www.datadosen.se/riverlayout/
JFrame frame = new JFrame("Test RiverLayout");
Container container = frame.getContentPane();
container.setLayout(new RiverLayout());
container.add("left", new JLabel("Label 1"));
container.add("tab", new JTextField("Text field 1"));
container.add("br left", new JLabel("Label 2"));
container.add("tab", new JTextField("Text field 2"));
frame.pack();
frame.setVisible(true);

Please suggest me a basic layout to use, other than the GridBag layout

OK I have a panel, and I want to place two panels on to it, left and right, such that the right panel should be double the width of the left side panel.
I want to add a menu to the left side panel, and the details of the selected item will appear in the right side panel.
Secondly, the size of the panels and their components should increase proportionately when the window is expanded (If any methods can be used for the purpose, please suggest!)
I did try to use the GridBagLayout but I think I have not yet been able to grasp it well. So please suggest the simplest layout manager which can serve my purpose.
EDIT:- PROBLEMS WITH WHAT I HAD TRIED WITH THE GRIDBAG
//Set Layout
setLayout(new GridBagLayout());
GridBagConstraints c= new GridBagConstraints();
//Set Layout constraints of components and add them to the MainPanel
c.gridx=0;
c.gridy=0;
c.weightx=0.5;
c.insets= new Insets(5,5,5,5);
c.fill=GridBagConstraints.BOTH;
add(iListPanel);
iListPanel.setBorder(BorderFactory.createTitledBorder("Check") );
GridBagConstraints c1= new GridBagConstraints();
c.gridx=1;
c.gridy=0;
c.weightx=1;
c.insets= new Insets(5,5,5,5);
c.fill=GridBagConstraints.BOTH;
add(iDetailsPanel);
iDetailsPanel.setBorder(BorderFactory.createTitledBorder("Check"));
Of the layout managers that come with Java, I think GridBagLayout is the simplest one that will do that. It's worth the time to learn it, because it's about the only layout manager that's halfway-competent. This should do it:
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c;
JPanel left = new JPanel();
left.setBorder(BorderFactory.createTitledBorder("Left"));
c = new GridBagConstraints();
c.weightx = 1;
c.weighty = 1;
c.fill = c.BOTH;
panel.add(left, c);
JPanel right = new JPanel();
right.setBorder(BorderFactory.createTitledBorder("Right"));
c = new GridBagConstraints();
c.weightx = 2;
c.weighty = 1;
c.fill = c.BOTH;
panel.add(right, c);
However, from the description of your problem, it sounds like JSplitPane will serve you better for this. It's a ready-made component to do more-or-less what you're asking, and has a user-resizeable separator as well. An example:
JSplitPane pane = new JSplitPane();
pane.setResizeWeight(1/3f); // right will be twice size of left
JPanel left = new JPanel();
left.setBorder(BorderFactory.createTitledBorder("Left"));
pane.setLeftComponent(left);
JPanel right = new JPanel();
right.setBorder(BorderFactory.createTitledBorder("Right"));
pane.setRightComponent(right);
Edit: The problem with your original code is that it does not use the constraints.
add(iListPanel);
should be:
add(iListPanel, c);
and likewise for iDetailsPanel.
You want to use a BorderLayout.
panel.add(panelLeft,"West");
panel.add(panelRight,"East");
North, South and Center is also available

How to set the component size with GridLayout? Is there a better way?

I am working on a larger GUI with Java and I am becoming angry on Layout Managers.
I have a "Settings-Panel" with a variable number of JComponents in it (Labels, Buttons, JSpinners, JSliders,...). I just want the following:
JLabel <-> JComponent
JLabel <-> JComponent
JLabel <-> JComponent
...
My Panel has a size of 500px, so that there is enough space for a lot of components. Unfortunately the GridLayout always stretches the size of the Components to the whole Panel, even if I set a MaximumSize for every component. It looks stupid if there are only two buttons each with a height of 250px.
I tried FlowLayout, but I cannot figure out a way to make new lines properly. I tried BoxLayout.Y_AXIS, but the Components are always centered, and Label and Component are not in the same line.
Does anybody know a good and short way with LayoutManagers to handle this properly?
An alternative to other layouts, might be to put your panel with the GridLayout, inside another panel that is a FlowLayout. That way your spacing will be intact but will not expand across the entire available space.
Don't use GridLayout for something it wasn't meant to do. It sounds to me like GridBagLayout would be a better fit for you, either that or MigLayout (though you'll have to download that first since it's not part of standard Java). Either that or combine layout managers such as BoxLayout for the lines and GridLayout to hold all the rows.
For example, using GridBagLayout:
import java.awt.*;
import javax.swing.*;
public class LayoutEg1 extends JPanel{
private static final int ROWS = 10;
public LayoutEg1() {
setLayout(new GridBagLayout());
for (int i = 0; i < ROWS; i++) {
GridBagConstraints gbc = makeGbc(0, i);
JLabel label = new JLabel("Row Label " + (i + 1));
add(label, gbc);
JPanel panel = new JPanel();
panel.add(new JCheckBox("check box"));
panel.add(new JTextField(10));
panel.add(new JButton("Button"));
panel.setBorder(BorderFactory.createEtchedBorder());
gbc = makeGbc(1, i);
add(panel, gbc);
}
}
private GridBagConstraints makeGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = x;
gbc.weighty = 1.0;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = (x == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.HORIZONTAL;
return gbc;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Layout Eg1");
frame.getContentPane().add(new LayoutEg1());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
For more complex layouts I often used GridBagLayout, which is more complex, but that's the price. Today, I would probably check out MiGLayout.
In my project I managed to use GridLayout and results are very stable, with no flickering and with a perfectly working vertical scrollbar.
First I created a JPanel for the settings; in my case it is a grid with a row for each parameter and two columns: left column is for labels and right column is for components. I believe your case is similar.
JPanel yourSettingsPanel = new JPanel();
yourSettingsPanel.setLayout(new GridLayout(numberOfParams, 2));
I then populate this panel by iterating on my parameters and alternating between adding a JLabel and adding a component.
for (int i = 0; i < numberOfParams; ++i) {
yourSettingsPanel.add(labels[i]);
yourSettingsPanel.add(components[i]);
}
To prevent yourSettingsPanel from extending to the entire container I first wrap it in the north region of a dummy panel, that I called northOnlyPanel.
JPanel northOnlyPanel = new JPanel();
northOnlyPanel.setLayout(new BorderLayout());
northOnlyPanel.add(yourSettingsPanel, BorderLayout.NORTH);
Finally I wrap the northOnlyPanel in a JScrollPane, which should behave nicely pretty much anywhere.
JScrollPane scroll = new JScrollPane(northOnlyPanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Most likely you want to display this JScrollPane extended inside a JFrame; you can add it to a BorderLayout JFrame, in the CENTER region:
window.add(scroll, BorderLayout.CENTER);
In my case I put it on the left column of a GridLayout(1, 2) panel, and I use the right column to display contextual help for each parameter.
JTextArea help = new JTextArea();
help.setLineWrap(true);
help.setWrapStyleWord(true);
help.setEditable(false);
JPanel split = new JPanel();
split.setLayout(new GridLayout(1, 2));
split.add(scroll);
split.add(help);
You need to try one of the following:
GridBagLayout
MigLayout
SpringLayout
They offer many more features and will be easier to get what you are looking for.
I used WrapFlowLayout instead
JPanel yourPanel = new JPanel(new WrapFlowLayout(10, 10);

How the swing's BoxModel works?

Let's say I would like to create a simple calculator. It consists of 3 fields. Text field to show result, field with checkboxes to select system and field with numbers.
What kind of component should I use for each element ?
How can I position elements in my window ?
How can I position elements inside component (ie checkboxes) ?
This is what I'm trying to achieve.
http://img28.imageshack.us/img28/7691/lab8c.jpg
I would use
JTextField for the number-window
JRadioButton for the radio buttons, and
JButton for the buttons.
The layout of the components should be deferred to a so called layout-manager. (Have a look at Using Layout Managers. In this case a GridLayout and/or a GridBagLayout would do fine.
This code should get you started:
import java.awt.*;
import javax.swing.*;
public class FrameTest {
public static void main(String[] args) {
final JFrame f = new JFrame("Frame Test");
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
panel.add(new JTextField(), gbc);
JPanel numSysPanel = new JPanel(new GridLayout(1, 3));
numSysPanel.setBorder(BorderFactory.createTitledBorder("Number System"));
numSysPanel.add(new JRadioButton("oct"));
numSysPanel.add(new JRadioButton("dec"));
numSysPanel.add(new JRadioButton("hex"));
panel.add(numSysPanel, gbc);
JPanel buttons = new JPanel(new GridLayout(4, 4, 2, 2));
for (int i = 0; i < 16; i++)
buttons.add(new JButton("" + i));
panel.add(buttons, gbc);
f.setContentPane(panel);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
First off, you start with determining, which LayoutManager you should use, to arrange your three fields. GridBagLayout will definitely do what you want, but is quite hard to program. You could try to get away with the simpler BorderLayout, which will make your application look odd, while resizing. You can use GroupLayout too. BoxLayout, GridLayout and FlowLayout are not what you want to use. Now you have a lot of options, to lay out you top elements.
Use a JTextField for the result. Use JCheckBox for the checkboxes, which you put insider a JPanel with an etched border (via JPanel.setBorder(BorderFactory.createEtchedBorder())) and a FlowLayout. Don't forget to put the checkboxes in a CheckboxGroup. Last but not least use a JPanel to group the JButtons for the, uhh, buttons. Use a GridLayout (5 rows, 4 columns) to arrange these buttons.

Categories