BoxLayout can't be shared error? [duplicate] - java

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.

Related

jLabel and jTable conflict [duplicate]

I am extremely new to Java Swing, and I'm having quite a bit of issues getting a nice layout going. I have checked out google, and even other answers on this website, but no information I find seems to solve the issue. Here is the result of my efforts:
As you can see, the label, text field, and button are all out of alignment. It is my goal for all of them to have the same left-hand border, and for the button and text field to have the same right-hand border, with these left and right hand borders being each the same distance from the left and righthand sides of my window.
Here are the important parts of my code:
public void run()
{
JFrame frame = new JFrame("Arduino Server");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
InstancePanel = new ServerGUIPanel();
frame.getContentPane().add(InstancePanel);
frame.pack();
frame.setVisible(true);
}
And, in ServerGUIPanel.java:
public ServerGUIPanel()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setPreferredSize(new Dimension(500, 500));
setBorder(new EmptyBorder(10, 10, 10, 10));
StatusLabel = new JLabel("STATUS: BOOTUP");
add(StatusLabel);
PortField = new JTextField();
PortField.setPreferredSize(new Dimension(5000, 20));
PortField.setMaximumSize(PortField.getPreferredSize());
PortField.setActionCommand("PortChanged");
add(PortField);
ConnectionButton = new JButton();
ConnectionButton.setPreferredSize(new Dimension(5000, 20));
ConnectionButton.setMaximumSize(ConnectionButton.getPreferredSize());
ConnectionButton.setActionCommand("ConnectionClicked");
add(ConnectionButton);
}
Does anyone have a simple solution to this? What am I doing wrong here?
Thank you very much!
--Georges Oates Larsen
Read the section from the Swing tutorial on How to Use BoxLayout for the basics of using a BoxLayout as well as a section on alignment issues.
Basically you need to make sure the alignmentX value of all components is set to be left aligned.
Also:
Don't use setPreferredSize() to set the size of a component. Each Swing component will determine its own preferred size.
Use Java naming conventions. Variable names should NOT start with an upper case character.
I would not recommend using setPreferredSize() AND setMaximumSize(). The latter will cause problems when stretching your main frame. [Your components will likely not want resize]
You should be using layout managers to handle all the alignments itself. I would stay away from using BoxLayout in this case, as different components want to size differently, and that will sway the alignment when added into your BoxLayout panel.
Moreover, you might want to give your main frame a layout as well.
Can you post how you used your GridBagLayout?

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.

avoid boxlayout overlapping

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.

Two Different Panels in One Frame - Java

I have a question.
I have one main frame, and to the left i have a sidebar with menus.
My question is, is it possible to make another panel within the main frame,
so that if menu1 is clicked, the related contents should be displayed to the second half of the main frame, and when other menus are pressed then obviously the relevant stuff according to what is selected. its a bit hard to explain, sorry. Has anyone got an idea, whether that is possible in Java with Eclipse?
yes this's pretty possible you have look at CardLayout, this LayoutManager could be provide the simple way how to implement switching betweens JPanel in the JFrame
Yes, you can add 2 JPanels to 1 frame.
JFrame frame = new JFrame();
JPanel pane1 = new JPanel();
JPanel pane2 = new JPanel();
frame.add(pane1, BorderLayout.WEST);
frame.add(pane2, BorderLayout.EAST);

Java GUI layout problems

I'm writing a small Java GUI program, and I'm having some issues with Java not laying things out properly. I haven't done much Java GUI code lately, so I'm having trouble seeing where the problem lies.
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart, false);
chartPanel.setPreferredSize(new Dimension(500, 270));
JPanel buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(500,50));
JButton toggleButton = new JButton("Toggle");
final JTextField minRange = new JTextField("10");
final JTextField maxRange = new JTextField("1000");
JButton setLimits = new JButton("Set Limits");
buttonPanel.add(toggleButton, BorderLayout.NORTH);
buttonPanel.add(minRange, BorderLayout.SOUTH);
buttonPanel.add(maxRange, BorderLayout.SOUTH);
buttonPanel.add(setLimits);
JSplitPane jsp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, chartPanel, buttonPanel);
jsp.setDividerLocation(0.8);
setContentPane(jsp);
What's happening here is that all of the layout options are completely being ignored. The GUI components are showing up properly, and the divider specifically is ignoring the preferred size of JFreeChart, and squeezing it to about 5% of space at the top of the frame.
In addition to problems with the splitpane not respecting your desired sizes, you are using BorderLayout constants but you haven't specified the layout for the panel (the default is FlowLayout).
This:
JPanel buttonPanel = new JPanel();
Should be:
JPanel buttonPanel = new JPanel(new BorderLayout());
I believe that using a float proportion on JSplitPane only works once the split pane is "realized", otherwise you're getting a proportion of zero because it doesn't know how big its going to be.
also:
buttonPanel.add(minRange, BorderLayout.SOUTH);
buttonPanel.add(maxRange, BorderLayout.SOUTH);
BorderLayout only allows one component to be in each area, so min range will never appear, as maxRange is now "the" south component. if you want both you'll need to put those 2 components in another panel, then add that panel to the south.
Try setting the minimum size too.
See: Java GUI Problems
JSplitPane pays attention to the minimum size, not the preferred size. Try simply changing setPreferredSize to setMinumumSize.
Dan Dyer is correct, you didn't set the Layout.
You could also set it by buttonPanel.setLayout(new BorderLayout())
And John Gardner is correct that you set a component to BorderLayout.SOUTH twice.
Also check out MigLayout if you don't already know about it. Its the least "surprising" layout manager I've ever used. It just works. It takes some learning, but very straight forward once you get over the syntax.
And I would avoid SplitPane if you can...its very finicky
Never call setPreferredSize() - it should be a calculation.
For example, your ButtonPanel is being set to a fixed preferred size.
What if you add I18N support and the user is using a language with very long localizations? What if the user resizes the frame?
Check out my article on layout managers for details on how you should really use them. It's from 1999 but still applies:
http://java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/
Enjoy!

Categories