Can anybody explain why circular reference is being set twice in the followig code?
//declare panel
this.cntnrPnl = new JPanel();
//define layout manager for the panel - but why circ ref?
this.cntnrPnl.setLayout(new BoxLayout(this.cntnrPnl, BoxLayout.Y_AXIS));
Why is it necessary to link the BoxLayout back to the JPanel container explicitly instead of JPanel.setLayout doing the setting itself behind the scene and using a setter from BoxLayout for code compactness?
E.g.:
this.cntnrPnl.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
//and then in JPanel.setLayout have something line
_layout.setContainer(this);
Because BoxLayout is a special layout that needs a reference to the target container it lays out. That's not the case of all the layout managers. It would be ugly to add a specific case for BoxLayout in the setLayout() method. And it would also mean that the BoxLayout would be in an unstable state after its construction, since it wouldn't have the mandatory target container yet.
The reverse could have been done though: having the BoxLayout constructor call setLayout(this) on the target container. But I don't know why it hasn't been done.
Why is it necessary to link the BoxLayout back to the JPanel container explicitly instead of JPanel.setLayout doing the setting itself behind the scene and using a setter from BoxLayout for code compactness?
What you call JPanel.setLayout is actually Container.setLayout:
public void setLayout(LayoutManager mgr)
You call call the method with a BoxLayout because it implements LayoutManager. But LayoutManager does not have a setContainer method, so it would not have worked without adding that method. But it seems that most layout managers don't care about a container so the method would not belong there.
Would it be possible for BoxLayout constructor to do the magic? Maybe not, though a BoxLayout is tied to a Container, the reverse is not necessarily true. Consider:
this.cntnrPnl = new JPanel();
BoxLayout bY = new BoxLayout(this.cntnrPnl, BoxLayout.Y_AXIS);
BoxLayout bX = new BoxLayout(this.cntnrPnl, BoxLayout.X_AXIS);
Now at different times you can call this.cntnrPnl.setLayout(bX) and this.cntnrPnl.setLayout(bY).
So looking at all options, it seems the current API is best, though of course all this is somewhat subjective.
By the way, please consider renaming cntnrPnl to containerPanel. You are not really saving much by stripping the vowels.
Because a JPanel is not the only available container in Swing. In particular, you might create your own container class and not know about those special requirements for BoxLayout. As a result, the layout manater would not work for your implementation.
Now one could ask why the BoxLayout needs a reference to the JPanel to begin with, but this is a different matter.
Related
I created a jframe, added a jbutton to it, and set the size of the jframe as 500,500 and size of the jbutton as 40,60. However, when I executed my program, my jbutton was covering the whole of my jframe. I
tried many things and looked into many sources, but I could not find a solution.
Please help me solve this.
You're not using a LayoutManager of any kind. The JButton will try to inherit the size of the parent container, as the default for a JFrame is BorderLayout (specifically, BorderLayout.CENTER). You could try using
button.setPreferredSize(x, y);
However I don't think this would be enough by itself. Call getContentPane on the Jframe, and set a layout on that contentPane container (I use FlowLayout a lot, as it respects setPreferredSize). Put your JButton inside that.
This is always a good starting point:
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
As the methods that you can call on a UI element vary depending on what LayoutManager you're assigning them to (be the child of). Sometimes it's setMinimumSize, sometimes it's setPreferredSize, and sometimes it's a combination.
I am trying to create a new JTextField in my Jframe. I want to play around with the positioning of the textfield. I tried using setBounds and setLocation to change the position of the text box but it doesn't change the location of the text box at all.
This is my code:
public class GUI_Tutorial extends JFrame {
public static void main(String[] args) {
GUI_Tutorial frame = new GUI_Tutorial();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(1000, 800);
frame.setVisible(true);
frame.setTitle("Calculator");
frame.setLayout(new FlowLayout());
}
public GUI_Tutorial() {
//frame.setLayout(new FlowLayout());
JTextField num1;
num1 = new JTextField(10);
add(num1);
num1.setVisible(true);
num1.setLocation(5, 5);
}
}
May I know what am I doing wrong?
Your problem is one of layout managers. When you add a component to a container, the layout manager will dictate where the component will go. A JFrame's contentPane (the JFrame sub-container that holds its components) uses a BorderLayout by default, and items added to this container in a default manner will fill the central portion of the container, will fill it completely if nothing else is added to other BorderLayout locations.
Possible solutions for placing items:
The worst suggestion, use a null layout. You would do this by calling getContentPane().setLayout(null);. But when you do this, you the programmer are 100% responsible for the exact position and size of all components added. This leads to hard to maintain GUI's that might not even work on other platforms -- so don't do this.
Use a GUI builder to help build your program: this has definite advantages, one being that it shields you from having to directly understand the layout managers, but this also is a disadvantage, because once you run into edge cases (and you usually will and quickly) that knowledge is essential. My own view is to initially avoid using this so as to better understand the layout managers, and then once you're familiar with the managers, then sure use this as needed.
Better is to learn and experiment with the layout managers, and Borders, playing with placement of components. Remember that you can nest containers (usually JPanels) and each can be given its own layout manager, allowing for complex GUI's that are created easily and maintained easily.
Note that
(again) JFrames (actually their contentPanes), JDialogs, and other top-level windows use BorderLayout by default, that JPanels use FlowLayout by default, that JScrollPanes use their own specialty layout, one that you will likely never want to muck with, and that most other components/containers, such as JComponent, JLabel,... have null layouts by default.
Best resource is the tutorial: Lesson: Laying Out Components Within a Container
Borders can also be useful here, especially the EmptyBorder which can allow you to put a blank buffer zone around your components.
Start playing with the simpler layout managers, FlowLayout, BorderLayout, GridLayout, then BoxLayout, before moving to the more complex
Try removing frame.setLayout(new FlowLayout());. You'll then need to use num1.setBounds(x, y, width, height) rather than setLocation()
But, as other users have pointed out, you should be using a layout manager. Read up on the different layouts and choose the best one for your GUI.
In my GUI class I have an array of textfields, which I initialized in this class constructor. The code is as follows
JTextField[] arrayOne= new JTextField [10];
for(int a = 0;a < 10;a++)
{
arrayOne[a] = new JTextField(String.valueOf(0));
arrayOne[a].setBounds(189 + a * 50, 156, 39, 23);
arrayOne[a].setVisible(true);
}
The problem is, that when I run my GUI, it does not show these text fields. Why not?
You should add the JTextField in the layout.
You should use add method of the container/or the class if you extend JFrame inside the for.
Read this.
Adding Components to a Container
When you add components to a panel or content pane, the arguments you
specify to the add method depend on the layout manager that the panel
or content pane is using. In fact, some layout managers do not even
require you to add the component explicitly; for example, GroupLayout.
For example, BorderLayout requires that you specify the area to which
the component should be added (using one of the constants defined in
BorderLayout) using code like this:
pane.add(aComponent, BorderLayout.PAGE_START); The how-to section for
each layout manager has details on what, if any, arguments you need to
specify to the add method. Some layout managers, such as GridBagLayout
and SpringLayout, require elaborate setup procedures. Many layout
managers, however, simply place components based on the order they
were added to their container.
Swing containers other than JPanel and content panes generally provide
API that you should use instead of the add method. For example,
instead of adding a component directly to a scroll pane (or, actually,
to its viewport), you either specify the component in the JScrollPane
constructor or use setViewportView. Because of specialized API like
this, you do not need to know which layout manager (if any) many Swing
containers use. (For the curious: scroll panes happen to use a layout
manager named ScrollPaneLayout.)
For information about how to add components to a specific container,
see the how-to page for the container. You can find the component
how-to pages using How to Use Various Components.
There is one more case for non visibility.
f.setVisible(true);
f.setSize(1000,1000);//Where f is the JFrame reference
Add the above statements after adding the JTextFields to the required Frame.
I am developing one java desktop application with a lots of panels with different and same layouts. Now when I want to set to panel new layout I always create new layout. E.G.
JPanel panel = new JPanel(new GridLayout(0, 1));
Is the correct solution to create some LayoutFactory and here create all the layouts that I need and then set to the panels?
1) laying JPanel by new GridLayout(0, 1) should be same as BorderLayout.CENTER or possible by using BoxLayout, in this case you place only one JComponent for whole JPanel
2) easiest way is lay JComponents by Nested Layout where each of Container can have different LayoutManager, same LayoutManager or their combinations
3) by using GridBagLayout or MigLayout is possible (in most of cases) place every JComponents once time for whole container or JPanel
hudi, if you want to make your code more concise, you can write helper methods which create and assign the layouts. If you are setting up layouts in only one class, the helper methods can be private methods of that class. Or if you are setting up layouts in various classes, you may be able to add protected helper methods to a common superclass (if you have one), or as static methods on a utility class.
Post the details of your code and we can give more specific suggestions.
I am learning Java Swing and I appended a menuBar to the frame. By default this should call jframe.getContentPane().add(child). When I ran the script the menuBar didn't show up. But the button was at the very top "y=0" if that makes sense.
Then I realized my mistake I actually had to put in a menu in the menubar. Then the menuBar showed up. So that got me thinking...is the "menubar" "contentpane" actually 2 panels? It is confusing the hell out of me. Because that acted a lot like a panel. But getContentPane() returns a Container, not a JPanel object so I'm confused.
If so, does that mean that the only thing that is dumped directly into a frame are just Jpanel objects? Hence JButtons, JLabels are not directly in a frame...
Does that mean, jpanels are "nested"?
One more thing that is confusing me. If a jpanel can control how things are positioned, what is a LayoutManager for? :S
Thanks, and please answer as if to a 2yr old asking why the sky is blue,ha ;)
Some random thoughts:
Yes, JPanels and other components are often "nested". This is where a firm understanding of the Swing/AWT layout managers is essential.
While the type returned by a JFrame's getContentPane() is technically a Container, it's also a JPanel (which inherits eventually from Container).
I believe that you can make anything that derives from Container the contentPane, but you need to take care that it is opaque.
for that there is method
frame.setJMenuBar(menuBar);
for todays Java Swing GUI, is not neccesary declare ContentPane, from Java5, and with BorderLayout as default LayoutManager
then frame.add(myPanel);
//is same as frame.add(myPanel, BorderLayout.CENTER) and occupated whole Container
basic stuff about how to use LayourManagers
getContentPane() always returns a Container instance. However, you should note that JPanel objects are Container instances, as well as other classes in the Swing framework. The actual class of the instance returned is irrelevant, as you do not have control over which implementation of Container is used as a contentPane (unless you have forced a specific contentPane), and most of the time this should not be a problem.
You can add many GUI widgets in a JFrame, such as JButton, JLabel, etc. However, they will be automatically added to the associated contentPane.
JPanel does not handle the objects positioning, the LayoutManager associated with your panel does; either automatically based on its own set of rules (e.g. FlowLayout), or by using the constraints you have specified when adding the object to the container (the GridBagLayout layout manager is a good example). The JavaDoc on the LayoutManagers usually contain enough information to get you started on using them.
You can have nested panels, yes. A Container can contain other Container instances. While it seems to be a complicated solution, it does enable you to control exactly how your GUI is displayed. Depending on which LayoutManager you are using, on the needs you have to fulfill with your user interface, and on your own preferences/habits as a developper, you might need less or more nested panels.
You need to see this API doc for JComponent.
If you look at the inheritance hierarchy, you will see that the JComponent extends Component so a JComponent is a Component.
Also under Direct Known Subclasses, you can see the list of all the classes that extend the JComponent including JMenuBar and JPanel.
So, JMenuBar and JPanel are two more specialized versions of JComponent (or Container).