avoid boxlayout overlapping - java

Here I go again... battling with swings!!! So I'm creating an online test which will be displayed in an applet. The number of questions in the tests isn't fixed, so I need to ask questions according to the test. In order to display the questions I created a question jpanel that then I added to container panel which be displayed in the applet. For the container panel I'm using a boxlayout that allows me to stack questions one on top of the other.
My issue is that after adding more than 5 questions to the container panel the questions start overlapping. So can anyone guide me?
First, how can I avoid the overlapping?
Second, does a jpanel have a fixed maximum size? Or is there a way I can make it big enough to fit all the test question in the panel container? I thought about embedding the panel in a jscrollpane or I don't know if once the container panel is embedded in the applet it will scroll down as I scroll down the browser... Thank you guys for any help
Here's a pic of what it looks like when there aren't many questions...
Here is the code...
public class Test extends JPanel {
public Test() {
setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(0, 5, 712, 1200);
add(scrollPane);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
MultipleChoice q1 = new MultipleChoice();
panel.add(q1);
MultipleChoice q2 = new MultipleChoice();
panel.add(q2);
MultipleChoice q3 = new MultipleChoice();
panel.add(q3);
MultipleChoice q4 = new MultipleChoice();
panel.add(q4);
MultipleChoice q5 = new MultipleChoice();
panel.add(q5);
}
}

I'm guessing, and all I can do is guess without an sscce, but if your MultipleChoice JPanel uses null layout, then it won't be able to give a decent preferredSize to your layout managers allowing for overlapping components. If so, again the solution is to not use null layout, almost ever.
You state in comment:
I know buddy... But how can I be more specific when I don't know much about swings? I'm using Windowbuilder and that's the layout given when setting a container layout to absolute.
"buddy"?
regarding, "when I don't know much about swings": then learn about Swing. Go to the Layout Manager Tutorials and read up on the layout managers.
regarding, "I'm using Windowbuilder and that's the layout given when setting a container layout to absolute.": part of your problem, as you yourself admit, is that you don't yet fully understand Swing and in particular use of its layout managers, and one reason for this problem is that you're using a tool that buffers you from having to understand this. I urge you not to use WindowBuilder. Again read up on the layout managers and learn how to use them. You will not be sorry that you've done this.

Related

BoxLayout can't be shared error? [duplicate]

This question already has answers here:
error upon assigning Layout: BoxLayout can't be shared
(4 answers)
Closed 7 years ago.
Hi there I am working on a Java app and below is an excerpt from a custom class called Gui which extends JFrame:
public Gui(){
super("EVC Scan & Price");
setSize(400,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
// GridLayout layout = new GridLayout(5,1);
BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
setLayout(layout);
//add header row
headerRow.setAlignmentX(Component.CENTER_ALIGNMENT);
BorderLayout layoutHeading = new BorderLayout();
headerRow.setLayout(layoutHeading);
if (headerImg != null){
ImageIcon icon = new ImageIcon(headerImg);
picLabel.setIcon(icon);}
headerRow.add(picLabel, BorderLayout.NORTH);
title.setAlignmentX(JLabel.CENTER_ALIGNMENT);
headerRow.add(title, BorderLayout.SOUTH);
add(headerRow);
//add first row
firstRow.setAlignmentX(Component.LEFT_ALIGNMENT);
BoxLayout layoutRow1 = new BoxLayout(firstRow,BoxLayout.Y_AXIS);
firstRow.setLayout(layoutRow1);
firstRow.add(catLabel);
scroll.setSize(390,100);
firstRow.add(scroll);
add(firstRow);
setVisible(true);
}
I have read many tutorials and the api and really can not see anything wrong with this, however the line reading: add(headerRow); seems to be the trigger for a "BoxLayout can't be shared" error.
If I change the layout for the JFrame to a flowlayout the nested boxlayout applied to the firstRow section works fine?
Can anyone help please?
Change this:
BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
to this:
BoxLayout layout = new BoxLayout(getContentPane(), BoxLayout.Y_AXIS);
The error-producing code passes the JFrame into the BoxLayout's constructor as the BoxLayout using container when in fact it's not. In truth, you're adding the layout to the JFrame's contentPane and not the JFrame.
As an aside, you may be painting yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. In fact, I would venture that most of the Swing GUI code that I've created and that I've seen does not extend JFrame, and in fact it is rare that you'll ever want to do this. More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.

How can I align these JPanels on the bottom of the surrounding JPanel?

I am learning to use swing so please bear with me. Have a look at the attached screenshot:
These are JLabels within a JLabel within a JFrame. I would like to move these inner JLabel (which are randomly generated in size and color at runtime) to the very bottom as though they were books on a shelf. I know about Layout managers, though I can't quite seem to find the proper one to do what I want. This screenshot shows the result of specifying none, thus it should default to FlowLayout.
The inner JLabels are just .add()ed without any placement done. SetLocation appears to do nothing whatsoever.
Can you help me out?
If I were you I'd add put those JLabels inside of a JPanel with a boxlayout then align that with a border layout. Here is some code to help you out:
JLabel outer = new JLabel();
outer.setLayout(new BorderLayout(0,0));
/** Add inner JLabels here. The other you add them is the order they will appear from to right**/
JPanel bookshelf = new JPanel();
bookshelf.setLayout(new BoxLayout(toolbar, BoxLayout.X_AXIS));
//Add your jlabels to the bookshelf
outer.add(bookshelf, BorderLayout.SOUTH);
Here is a great tutorial on layout managers.
Also here is a UI I designed which is similar to what I think you want.
Hope this helps you out.

Centering a JLabel in a JPanel

I have a panel derived from JPanel. I have a custom control derived from JLabel. I am attempting to center this custom JLabel on my panel.
The only way I know to do this that will work is to use the a null layout (setLayout(null)) and then calculate the custom JLabel's setLocation() point so that it's in the right spot.
The custom JLabel is physically moved from one panel to this panel in this app and I believe the location previously set in setLocation is affecting things. However when I set it to (0,0) the component goes up into the upper left corner.
BorderLayout doesn't work because when only 1 component is provided and placed into BorderLayout.CENTER, the central section expands to fill all of the space.
An example I cut and pasted from another site used BoxLayout and component.setAlignmentX(Component.CENTER_ALIGNMENT). This didn't work either.
Another answer mentioned overriding the panel's getInset() function (I think that's what it was called), but that proved to be a dead end.
So far I'm working with a panel with a GridBagLayout layout and I include a GridBagConstraints object when I insert the custom JLabel into my panel. This is inefficient, though. Is there a better way to center the JLabel in my JPanel?
Set GridBagLayout for JPanel, put JLabel without any GridBagConstraints to the JPanel, JLabel will be centered
example
import java.awt.*;
import javax.swing.*;
public class CenteredJLabel {
private JFrame frame = new JFrame("Test");
private JPanel panel = new JPanel();
private JLabel label = new JLabel("CenteredJLabel");
public CenteredJLabel() {
panel.setLayout(new GridBagLayout());
panel.add(label);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
CenteredJLabel centeredJLabel = new CenteredJLabel();
}
});
}
}
Supose your JLabel is called label, then use:
label.setHorizontalAlignment(JLabel.CENTER);
Forget all the LayoutManagers in the Java Standard Library and use MigLayout. In my experience it's much easier to work with an usually does exactly what you expect it to do.
Here's how to accomplish what you're after using MigLayout.
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class Test
{
public static void main( String[] args )
{
JFrame frame = new JFrame( );
JPanel panel = new JPanel( );
// use MigLayout
panel.setLayout( new MigLayout( ) );
// add the panel to the frame
frame.add( panel );
// create the label
JLabel label = new JLabel( "Text" );
// give the label MigLayout constraints
panel.add( label, "push, align center" );
// show the frame
frame.setSize( 400, 400 );
frame.setVisible( true );
}
}
Most of that is just boilerplate. The key is the layout constraint: "push, align center":
align center tells MigLayout to place the JLabel in the center of its grid cell.
push tells MigLayout to expand the grid cell to fill available space.
BoxLayout is the way to go. If you set up a X_AXIS BoxLayout, try adding horizontal glues before and after the component:
panel.add(Box.createHorizontalGlue());
panel.add(label);
panel.add(Box.createHorizontalGlue());
I don't like the answers here.
I've never seen a valid use of a GridBagLayout ever in my career. Not saying there isn't one, just saying I haven't seen [a valid] one, and there might be correlation there. Moreover, adding a single JLabel to the middle of a Container might make it center for demonstrational purposes, but you're going to have a lot harder of a time later on if you try to continue to work with that over some other layouts.
I do like the suggestion about the BoxLayout, because that is actually a great way to do it. That said, that answer is only part of the puzzle, hence why I'm dredging up a 7 year old question.
My 'Answer'
Really there is no short answer to your question. There is an exact answer to your question based on what you asked, but StackOverflow is about a community learning from each other, and I suspect you're trying to learn how to use layouts in general (or you were 7 years ago) and telling you to type a combination of keys to do exactly your demo case is not going to teach you the answer.
I'm going to try not to explain any layouts that you can't web-search the answer for on your own (with a link to the Oracle tutorial at the end, because I think it explains the different layouts fairly well).
BoxLayout
BoxLayout is one way to do it, and there is already a code snippet to demo it above so I won't provide one. I'll expand on it to say that, just as mentioned, that only answers your question exactly, but doesn't really teach you anything. Glue, as the BoxLayout refers to it, basically gives you an equal amount of remaining real-estate between all the 'glue' currently in the Container. So, if you were to do something like
panel.add(Box.createHorizontalGlue());
panel.add(label);
panel.add(Box.createHorizontalGlue());
panel.add(otherLabel);
You would find that your JLabel is no longer centered, because the 'glue' is only the remaining real-estate left, after two JLabels were added to the Container which will be equally divided between the two 'slots' (two calls to Container#add(Component) with a glue parameter) in theContainer`.
BorderLayout
BorderLayout is another way to go about this. BorderLayout is broken down into 5 regions. BorderLayout#CENTER, as you might guess, is the center region. The important note about this layout and how it centers things is how it obeys sizes of the Component that is in the center. That I won't detail though; the Oracle tutorial at the end covers it well enough if you're interested, I think.
Worth Noting
I suppose you could use a GridLayout, but it's a more simple way to do it over a GridBagLayout, which I already said even that I think is not a good approach. So I won't detail this one either.
The Point of it All
Now all that said, I think all LayoutManagers are worth a look. Just like anything else with relation to programming - use the tool that fits the job. Don't just assume because you used X layout before, that you should always use X layout and no other layout is viable. Figure out what you want your display to look like, and how you think it should behave with respect to resizing components, and then pick what you think would work best.
Another dual meaning of picking the right tool, is that you don't have to just fit all of your components into one single Container and make one layout do everything. There is nothing stopping you (and I strongly encourage you to) use multiple Containers and group them all together. Control each Container with a layout that is appropriate for that section of the display, and a different layout for a different Container.
Important!!
The reason why this is very important is because each layout has rules and things that they obey, and other things that they respect, and then others that are effectively ignored (i.e. preferred, maximum, and minimum sizes, for instance). If you use different layouts [correctly], you will find your display accepts dynamically being resized while still obeying the shape that you wanted it to hold. This is a very important key difference between doing it the right way, and just settling with GridBagLayout.
JPanel outer = new JPanel(new BorderLayout());
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
JPanel southPanel = new JPanel(new CardLayout());
outer.add(centerPanel, BorderLayout.CENTER);
outer.add(southPanel, BorderLayout.SOUTH);
Figure out what is appropriate to your scenario, and go with that. There is no one-size-fits-all unless you want something overly cumbersome and made redundant by other layouts (i.e. GridBagLayout).
Oracle's Tutorial
If you've made it this far, then I think you're looking for as much information as you can get. In which case, I strongly encourage you to read Oracle's tutorial on layout managers because it lays out general details of them all very well: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
Use this.
labelName.setHorizontalAlignment(SwingConstants.CENTER);
or
labelName.setHorizontalAlignment(JPanel.CENTER);
Both of them must work.
Do like this instead of libraries and layouts :
JLabel jlabel = new JLabel("Label Text", SwingConstants.CENTER);
Make sure to import javax.swing.SwingConstants INTERFACE , BUT DO NOT IMPLEMENT IT. It contains only constants and no methods.
Put the JLabel in a JPanel or else it will come at the center of the JFrame or JWindow (your top level container).

Alignment of components in a gui window

I have got a window that looks like window1 and I would like it to look like window2:
This is my code:
String q = "Have you used GUI before?";
JLabel textLabel2 = new JLabel(
"<html><div style=\"text-align: center;\">" + q + "</html>", SwingConstants.CENTER);
add(textLabel2, BorderLayout.NORTH);
JPanel radioPanel = new JPanel();
add(radioPanel, BorderLayout.CENTER);
JPanel btnPanel = new JPanel();
add(btnPanel, BorderLayout.SOUTH);
For the radio-buttons, I tried to use GridLayout, but it broke the position of "Yes" and "No". And for the "back" and "next" buttons, horizontal alignment did not work (btnPanel.setAlignmentX(RIGHT_ALIGNMENT);), apparently. Any solutions will be highly appreciated, I'm stuck with this bit way too long. Thanks
--EDIT--
That is working perfectly fine:
btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.LINE_AXIS));
btnPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
btnPanel.add(Box.createHorizontalGlue());
so the buttons problem is solved.
However, still can't get the radio-buttons fixed.
--EDIT 2--
Fixed the background for the radio-buttons using setOpaque(false);
What do you mean by it "broke" the position of "yes" and "no" as a GridLayout should work just fine. I'd give it 1 column and 2 (or 0 for variable number of) rows via new GridLayout(0, 1). Be sure that its opaque property is set as false by doing radioPanel.setOpaque(false);. This way it will show the background color of the container that it sits in. You may need to make the JRadioButtons non-opaque as well, I'm not sure.
Your btnPanel could use a BoxLayout and use Box.createGlue() to push the buttons over to the right side.
Most importantly -- if you haven't yet done so, please read the tutorials on use of the Swing layout managers which you can find here.
A couple of things you can do about this. You need to change your LayoutManager. This is not a great task for BorderLayout. You could do nested BoxLayouts. A vertical box that has the vertical fixed height strut, label, vertical fixed height strut, yes radio, vertical fixed strut, no radio, Vertical glue, and the final button panel. Then use your edit in the button panel to horizontally align them. That's one option, but the nesting of the panels is annoying.
Another option go get TableLayout and learn how to use it. TableLayout is one of the best LayoutManagers. It's easy to use, solidly tested, and it makes Swing fun again. You'll never use GridBagLayout ever ever ever again.
http://java.sun.com/products/jfc/tsc/articles/tablelayout/
The final option is use the new GroupLayout. I'm not terribly familiar with it, but it looks pretty easy. And, it doesn't take as much code or nesting unnecessary panels like Box does.

Merge two tabs in Java Swing

Thank you for viewing. I'm a beginner with Java swing. I'm trying to merge two tabs in an application. The tabs are created in this way:
pane=new JTabbedPane(JTabbedPane.TOP, JTabbedPane.WRAP_TAB_LAYOUT);
pane.add(panel1);
pane.add(panel2);
I'd like to have the contents of panel1 and panel2 merged together, with panel2 displayed underneath panel1. I know this may seem like a very simple question, but I am still learning. Thanks guys.
Edit: panel1 and panel2 are both JScrollPane
Create a third JPanel that uses whatever layout would work (BorderLayout or BoxLayout come to mind), and add your two JPanels to the third one. Then add the third one to the tabbed pane.
edit: this is a little confusing: "Edit: panel1 and panel2 are both JScrollPane" So these are in fact JScrollPanes, not JPanels? Regardless, my suggestion above still works. :)
Most important though: study how to use layout managers and components such as JPanels etc on the Oracle Swing Tutorials: Layout Manager Tutorial
JPanel containerPanel = new JPanel();
containerPanel.setLayout(new BoxLayout(containerPanel, BoxLayout.PAGE_AXIS));
containerPanel.add(panel1);
containerPanel.add(panel2);
pane.add(containerPanel);

Categories