createVerticalGlue() in BoxLayout not functioning - java

I have used the createVerticalGlue() successfully on a number of times. However in the following screen building code it is not working. I am still wondering why.
The situation is that I have two JPanels (leftPanel, rightPanel) within another Panel (centralPanel). Each of these two panels will host two JComponents using a BoxLayout Y-Axis. I want to distribute the remaining free space before, between and after the two JComponents.
I know that I can use empty borders and rigid areas to solve the problem but it happens that I am a bit hard headed!
My appologies for the long question.
public class MemberGUI extends JFrame {
JPanel contPane = (JPanel) this.getContentPane();
JPanel centralPanel = new JPanel();
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
JPanel lowerPanel = new JPanel();
JLabel title = new JLabel("Add/Delete Member");
JLabel nameLbl = new JLabel("Member's name");
JLabel idLbl = new JLabel ("Member ID");
JTextField nameFld = new JTextField(10);
JTextField idFld = new JTextField(10);
public void buildMe(){
//LayoutManagers
contPane.add(title,BorderLayout.PAGE_START);
contPane.add(centralPanel,BorderLayout.CENTER);
contPane.add(lowerPanel,BorderLayout.PAGE_END);
centralPanel.add(leftPanel);
centralPanel.add(rightPanel);
leftPanel.setLayout(new BoxLayout(leftPanel,BoxLayout.Y_AXIS));
rightPanel.setLayout(new BoxLayout(rightPanel,BoxLayout.Y_AXIS));
//leftPanel.add(Box.createRigidArea(new Dimension(0,50)));
leftPanel.add(Box.createVerticalGlue());
leftPanel.add(idLbl);
leftPanel.add(Box.createVerticalGlue());
leftPanel.add(nameLbl);
leftPanel.add(Box.createVerticalGlue());
//rightPanel.add(Box.createRigidArea(new Dimension(0,50)));
rightPanel.add(Box.createVerticalGlue());
rightPanel.add(idFld);
rightPanel.add(Box.createVerticalGlue());
rightPanel.add(nameFld);
rightPanel.add(Box.createVerticalGlue());
// JFrame Settings
this.setSize(500,400);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}

afaics, centralPanel has default layoutManager, which is FlowLayout. This always sizes its children to their prefSize, so the glue never comes into play.
Nesting containers comes at a price (which nesting wizards like #Andrew happily pay :-) Also, it's not entirely trivial to get right (f.i. replace the upper textField with a comboBox to see the mis-alignment). In the longer run, there's hardly a route around learning to master a more powerful manager, like f.i. MigLayout (my current personal favorite)

Related

How to Keep JCheckBox Horizontally inside JPanel

I have a JPanel. Inside Panel I have kept one JLabel and three JCheckBox.
I want to keep all the checkBox in one line after JLabel. Here is the sample code and some screenshots.
Output 1
Output 2
When i change to X_AXIS it is coming everything in one line and when i switch to Y_AXIS then it is coming new line means vertically.
But my requirement is all the checkbox should come next line means after JLabel.
JLabel should come in line and all the checkBox should come in one line.
public class CheckBoxWithJLabel {
public static void main(String[] args) {
JFrame f= new JFrame("CheckBox Example");
JPanel panel = new JPanel();
panel.setBounds(40,80,600,200);
JCheckBox chk_Embrodary=new JCheckBox("Embrodary");
JCheckBox chk_Cutting=new JCheckBox("Cutting");
JCheckBox cb_Sewing=new JCheckBox("Sewing");
panel.setLayout(new javax.swing.BoxLayout(panel, javax.swing.BoxLayout.X_AXIS));
JLabel lblHeader=new JLabel("Job Work Process Selection");
panel.add(lblHeader);
panel.add(chk_Embrodary);
panel.add(chk_Cutting);
panel.add(cb_Sewing);
f.add(panel);
f.setSize(600,400);
f.setLayout(null);
f.setVisible(true);
}
}
I want this output like
this
How to solve this problem?
I would highly suggest you to have a look through the Java Swing Tutorial, especially the Laying Out Components Within a Container section, since it seems you lack some basic understanding of how Swing and its Layout Managers are supposed to be used.
Regarding your problem:
Currently, you are using a single BoxLayout, which " puts components in a single row or column". You only want that behavior for your JCheckBoxes though, and not for your JLabel. Keeping this in mind, the solution is to split up your components and to not put all of them in a single JPanel. Doing this will grant you more flexibility in how you design your GUI, since you can use multiple layouts in different nested panels.
You could do something like this (explanation in the code comments):
public static void main(String[] args) {
JFrame f = new JFrame("CheckBox Example");
// add a Y_AXIS boxlayout to the JFrames contentpane
f.getContentPane().setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
JCheckBox cbEmbrodary = new JCheckBox("Embrodary");
JCheckBox cbCutting = new JCheckBox("Cutting");
JCheckBox cbSewing = new JCheckBox("Sewing");
// no need to set the bounds, since the layoutmanagers will determine the size
JPanel labelPanel = new JPanel(); // default layout for JPanel is the FlowLayout
JLabel lblHeader = new JLabel("Job Work Process Selection");
labelPanel.add(lblHeader); // JPanel for the label done
// JPanel for the comboboxes with BoxLayout
JPanel cbPanel = new JPanel();
cbPanel.setLayout(new BoxLayout(cbPanel, BoxLayout.X_AXIS));
cbPanel.add(cbEmbrodary);
cbPanel.add(cbCutting);
cbPanel.add(cbSewing);
f.add(labelPanel);
f.add(cbPanel);
// No need to set the size of the JFrame, since the layoutmanagers will
// determine the size after pack()
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
Output:
Sidenotes:
Don't set fixed sizes via setSize() or setBounds() to your components. Swing is designed to be used with appropariate LayoutManagers, and if you do that, calling pack() on the JFrame before setting it visible will layout the components and determine their appropriate size. (Also, don't use null-layout for the same reasons)
If you need the JLabel to not be centered but left aligned, like in your screenshot, then use the following:
FlowLayout layout = (FlowLayout) labelPanel.getLayout();
layout.setAlignment(FlowLayout.LEFT);

Java: What Layout Manager would be best for a game menu?

===================
Game Name
Play
Exit
===================
the above is what my previous game menu looked like. I used the Box Layout to create it but it was very tedious. Is there there a better layout manager that I could use?
here is the code for those that asked of the main pane.
private JButton JB;
private JButton EB;
private JOptionPane JO;
public StartUpWindow(){
super("Pong");
JPanel outside = new JPanel();
JPanel inside = new JPanel();
setLayout(new BorderLayout());
outside.setLayout(new BoxLayout(outside, BoxLayout.LINE_AXIS));
inside.setLayout(new BoxLayout(inside, BoxLayout.PAGE_AXIS));
outside.add(Box.createHorizontalStrut(280));
outside.add(inside);
outside.add(Box.createHorizontalStrut(20));
inside.add(Box.createVerticalStrut(20));
JLabel title = new JLabel(" "+"Pong");
title.setFont( new Font("Serif", Font.BOLD, 40));
inside.add(title);
inside.add(Box.createVerticalStrut(20));
JButton btt1 = new JButton("Start");
Dimension d = new Dimension(200,40);
btt1.setSize(d);
btt1.setMinimumSize(d);
btt1.setMaximumSize(d);
btt1.setPreferredSize(d);
JButton btt2 = new JButton("Credits");
btt2.setSize(d);
btt2.setMinimumSize(d);
btt2.setMaximumSize(d);
btt2.setPreferredSize(d);
JButton btt3 = new JButton("Exit");
btt3.setSize(d);
btt3.setMinimumSize(d);
btt3.setMaximumSize(d);
btt3.setPreferredSize(d);
inside.add(btt1);
btt1.addActionListener(this);
btt1.setActionCommand("start");
inside.add(Box.createVerticalStrut(5));
inside.add(btt2);
btt2.addActionListener(this);
btt2.setActionCommand("credits");
inside.add(Box.createVerticalStrut(5));
inside.add(btt3);
btt3.addActionListener(this);
btt3.setActionCommand("exit");
inside.add(Box.createVerticalStrut(20));
add(outside);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
this.setVisible(true);
this.setResizable(false);
this.setLocation(450,200);
inside.setBackground(Color.GRAY);
outside.setBackground(Color.GRAY);
}
I agree that BoxLayout is tedious but I admire its relative simplicity.
Another quick and easy option is to use the "javax.swing.Box" class instead of using a layout manager directly.
Box box = Box.createVerticalBox();
box.add(new JLabel("Game"));
box.add(Box.createVerticalStrut(20));
box.add(new JLabel("Button 1"));
box.add(new JLabel("Button 2"));
JFrame frame = new JFrame();
frame.add(box);
frame.pack();
frame.setVisible(true);
Box offers a number of useful methods. You can use it to create vertical and horizontal boxes, create "struts" to reserve horizontal and vertical space, and create "glue" to fill in available space when the layout grows.
Of course you could also use GridBagLayout, but I tend to reserve it for more complex layouts. Box and his cousin BoxLayout are often good enough for simple layouts and are easy for new programmers who are maintaining the application to understand and debug.
Why not simply use no layout and instead draw everything using a Graphics object?
You could easily achieve this by creating a BufferStrategy bound to the Window object (invoke createBufferStrategy on the latter) then call a few simple methods to easily redraw the screen.
This also means it's simpler to then code the game's display when you're playing it.
BufferStrategy also allows the use of page flipping and other forms of buffering when the application is in fullscreen exclusive mode, allowing it to refresh the screen very rapidly in many applications.

Easy and Quick Layout for Java Swing

I really come from Web Development and I rarely do anything with Swing. However, today I am trying to achieve some simple GUI in Swing, but I'm having trouble because I don't have the time (...yeah, maybe it's rather the lack of interest because I don't see the need to learn it) on understanding GridLayout, GridBagLayout and others in deep...
So, I just want something like the following (each X is a component):
X X X X
X
And all be centered, which is already working. What I don't manage to do is to just find a Layout where I can simply arrange X Components in one row, and then only one in the next, no special alignment needs there...
What's the easiest / cleanest way of getting such a layout with Swing?
What about this:
private static JPanel createPanel() {
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
final JPanel firstRowPanel = new JPanel();
firstRowPanel.setLayout(new BoxLayout(firstRowPanel, BoxLayout.X_AXIS));
firstRowPanel.add(new JLabel("X"));
firstRowPanel.add(new JLabel("X"));
firstRowPanel.add(new JLabel("X"));
firstRowPanel.add(new JLabel("X"));
final JPanel secondRowPanel = new JPanel();
secondRowPanel.setLayout(new BoxLayout(secondRowPanel, BoxLayout.X_AXIS));
secondRowPanel.add(Box.createHorizontalGlue());
secondRowPanel.add(new JLabel("X"));
secondRowPanel.add(Box.createHorizontalGlue());
panel.add(firstRowPanel);
panel.add(secondRowPanel);
return panel;
}

Java Positioning a list on a GUI

I'm trying to add a JList to a GUI, but am wondering how to position it? I want it to appear on the right hand side of the TextArea for data that will be sent to the GUI for selection.
Can anyone suggest how to do this? Here is the code (note: very new to Java and GUI's)
protected static void createAndShowGUI() {
GUI predict = new GUI();
JFrame frame = new JFrame("Phone V1.0");
frame.setContentPane(predict.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setMinimumSize(new Dimension(300, 400));
frame.setVisible(true); // Otherwise invisible window
}
private JPanel createContentPane() {
JPanel pane = new JPanel();
TextArea = new JTextArea(5, 10);
TextArea.setEditable(false);
TextArea.setLineWrap(true);
TextArea.setWrapStyleWord(true);
TextArea.setWrapStyleWord(true);
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
//Adds the buttons from Top to Bottom
String[] items = {"dsfsdfd"};
list = new JList(items);
JScrollPane scrollingList = new JScrollPane(list);
int orient = list.getLayoutOrientation();
JPanel window = new JPanel();
pane.add(window);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 3));
JButton[] buttons = new JButton[] {
new JButton("Yes"),
new JButton(""),
new JButton("Clr"),
new JButton("1"),
new JButton("2abc"),
new JButton("3def"),
new JButton("4ghi"),
new JButton("5jkl"),
new JButton("6mno"),
new JButton("7pqrs"),
new JButton("8tuv"),
new JButton("9wxyz"),
new JButton("*+"),
new JButton("0_"),
new JButton("^#")
}; // Array Initialiser
for (int i = 0; i < buttons.length; i++) {
buttonPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}
pane.add(TextArea);
pane.add(list);
pane.add(buttonPanel);
return pane;
}
Read the section from the Swing tutorial on Using Layout Mananger. There is no need to only use a single layout manager. You can nest layout managers to get the desired effect.
Wrap your TextArea and list in a new panel with a BorderLayout manager. Basically the BorderLayout manager lets you arrange components using north, south, east, west and center coordinates. The components at the center takes all available space as the parent container has more space available to it.
private JPanel createContentPane() {
JPanel pane = new JPanel(); //this is your main panel
JPanel textAreaPanel = new JPanel(new BorderLayout()); //the wrapper
//Some more code...
//Then at the end
//Make your TextArea take the center
textAreaPanel.add(TextArea, BorderLayout.CENTER);
//And the list to the east
textAreaPanel.add(list, BorderLayout.EAST);
pane.add(textAreaPanel);
pane.add(buttonPanel);
return pane;
}
The cool thing is that you can nest panels inside other panels, adding them different layout managers to get your desired layout.
On an unrelated note, try to follow Java naming conventions. Instead of JTextArea TextArea use JTextArea textArea. It makes it easier for you and people reading your code to understand it.
You could use a layout manager like Mig Layout for that kind of positionning.
(source: miglayout.com)
I could recommend you FormLayout. Before I found this layout I had a real pain with GridBagLayout. FormLayout is more powerful and much more convenient to learn and use and it is free. Give it a chance.
As others suggested, familiarize yourself with the concept of layout managers. There are several that come with the standard Swing API and several good 3rd party ones out there.
In addition, you will want to add the JList to a scroll pane (JScrollPane). You may want to consider adding it to a split pane (JSplitPane). And by consider I don't mean "do it because some guy on the net said so" I mean "do it if it makes sense for your end users".

How can I set a JPanel maximum or preferred size that uses gridLayout?

I had problem using a very simple frame containing two JPanel.
The problem is on the layout of the Center JPanel that contains four JButton.
How can I set a better size for buttons or directly for JPanel that uses the GridLayout. On the picture the problem:
alt http://img42.imageshack.us/img42/4601/horrible.jpg
!
Here the code: ` JFrame window = new JFrame("Horrible! LOL");
JTextField textField = new JTextField("");
textField.setPreferredSize(new Dimension(200,20));
JPanel textPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
textPanel.add(textField);
window.add(textPanel, BorderLayout.NORTH);
JButton plus = new JButton("+");
//plus.setPreferredSize(new Dimension(50,50)); nothing would change
JButton minus = new JButton("-");
JButton per = new JButton("x");
JButton divide = new JButton("/");
JPanel prova = new JPanel(new GridLayout(2,2,10,10));
Dimension d = new Dimension(20,20);
prova.setMaximumSize(d); // nothing changed!
prova.add(plus);
prova.add(minus);
prova.add(per);
prova.add(divide);
window.add(prova, BorderLayout.CENTER);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(250,300);
window.setResizable(false);
window.setVisible(true);`
Which is a good solution?
Kind regards
Unfortunately gridlayout doesent respect preferred sizes. But still if you want to stick to grid layout then you can try something like this:
public static JComponent wrap(JComponent comp)
{
JPanel panel = new JPanel();
panel.add(comp);
return panel;
}
And then instead of direclty adding in to prova add like this:
prova.add(wrap(plus));
prova.add(wrap(minus));
prova.add(wrap(per));
prova.add(wrap(divide));
Tested, Works perfect!!
There are other better ways though
That's what happen to me:
It's definitely attached to the upper edge of the grid.
alt text http://img96.imageshack.us/img96/9431/stillnot.jpg
Even if in this case, in the wrap method I can set the preferredSize of buttons/comp, every buttons is on its own edge. What about others solutions. How would you position buttons for a calculator?
Kind regards and thanx angain!

Categories

Resources