I have a project to copy the google sign-in GUI here . So far I'm still searching on what I'm gonna start with, but after some research I think it is possible on BorderLayout to do this. Im getting how it works by readjusting everything through borders, and I kind of like it because it is quite responsive compared to having null layout and coding every setBounds for each component.
I've been imagining using a background panel, a panel for the fill up form,
and creating panels for each pair of label and textfields to properly create the space and stacking (or nesting) them on top of the other. Our teacher just told us to snip out the image, she just wants if we know how to design something out of scratch. That and also saving the input into a text file.
However, I can't seem to grasp the concept of increasing the component size inside the borders to imitate the gaps between the text fields, like some sort of a padding between components? Using setSize doesnt work and so far my search only results into resizing borders, or perhaps I still have not entered the right searachable term for it?
Also, Ive been looking for another way and I think this project will also work using GridBaglayout. However many people say GridBagLayout is too complicated. What do you think would be easier?
In my experience almost every (99%) of the panels using GridBagLayout can be designed by using all other layouts. So, someone could say that GridBagLayout is optional
In your situation, avoiding the use of a GridBagLayout is easy. Take a look at the following code:
public class NoGridBagLayout extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new NoGridBagLayout().setVisible(true));
}
public NoGridBagLayout() {
super();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setExtendedState(MAXIMIZED_BOTH);
JPanel borderPanel = new JPanel(new BorderLayout());
borderPanel.setBorder(new TitledBorder("borderPanel - BorderLayout"));
JLabel label = new JLabel("Create a google account.");
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(label.getFont().deriveFont(25f));
borderPanel.add(label, BorderLayout.PAGE_START);
setContentPane(borderPanel);
JPanel gridPanel = new JPanel(new GridLayout(1, 2));
gridPanel.setBorder(new TitledBorder("gridPanel - GridLayout"));
getContentPane().add(gridPanel, BorderLayout.CENTER);
JPanel leftBoxedPanel = new JPanel(); // Fill it with panels using BoxLayout.X_AXIS
leftBoxedPanel.setLayout(new BoxLayout(leftBoxedPanel, BoxLayout.Y_AXIS));
leftBoxedPanel.setBorder(new TitledBorder("leftBoxedPanel - BoxLayout.Y_AXIS"));
gridPanel.add(leftBoxedPanel);
JPanel rightBoxedPanel = new JPanel(); // Fill it with panels using BoxLayout.X_AXIS
rightBoxedPanel.setLayout(new BoxLayout(rightBoxedPanel, BoxLayout.Y_AXIS));
rightBoxedPanel.setBorder(new TitledBorder("rightBoxedPanel - BoxLayout.Y_AXIS"));
gridPanel.add(rightBoxedPanel);
}
}
Preview:
Related
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).
I am attempting to place two panels over the top of another two panels, so the positions match exactly. This will allow me to then paint over the top of the previous(bottom) panels. The reason for doing this, is that I have implemented a "drag a rectangle" zoom function, so on the panel the user will drag the mouse to draw a rectangle, and then the panel will become filled with the contents of that rectangle. However, I have now decided I would like include a visual representation of the rectangle as the user drags it.
Since I (assume) I cannot draw the rectangle on the bottom panel, since it already has a complicated paint on it anyway, I figured I would be able to draw it onto another panel that I would place on top. (If there is any easier way please shout!)
I am happy I have been able to get the panels into the correct position, using a BorderLayout/GridLayout combo, without the need for absolute positing, however the setOpaque method is not working on any of the three panels I have added. Does anyone know why this is?
Many thanks in advance, code below:
public void initiate() {
JPanel panel1 = new JPanel();
mandPanel mandDisplay = new mandPanel();
juliaPanel juliaDisplay = new juliaPanel();
JPanel detailsPanel = new JPanel();
JPanel bottomDetails = new JPanel();
JPanel panelForDisplays = new JPanel();
JPanel listenerPanelHolder = new JPanel();
JPanel listenerPanel = new JPanel();
JPanel blankPanel = new JPanel();
panelForDisplays.setLayout(new GridLayout(1,2));
detailsPanel.setLayout(new FlowLayout());
bottomDetails.setLayout(new FlowLayout());
panel1.setLayout(new BorderLayout());
panelForDisplays.add(mandDisplay);
panelForDisplays.add(juliaDisplay);
listenerPanelHolder.setOpaque(false);
listenerPanel.setOpaque(false);
blankPanel.setOpaque(false);
listenerPanelHolder.setLayout(new GridLayout(1,2));
listenerPanelHolder.add(listenerPanel);
listenerPanelHolder.add(blankPanel);
panel1.add(detailsPanel,BorderLayout.NORTH);
panel1.add(panelForDisplays,BorderLayout.CENTER);
panel1.add(listenerPanel,BorderLayout.CENTER);
panel1.add(bottomDetails, BorderLayout.SOUTH);
setContentPane(panel1);
setSize(width*2, height);
setResizable(false);
this.addWindowListener(new onClose(savedJulias));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
PS: A lot of code is omitted to avoid mess, but if anyone thinks they could solve with more code please say! Thanks :)
First off, adding two components at the BorderLayout.CENTER position replaces the first component with the 2nd, and so the 2nd doesn't cover the 1st, it displaces it. As per the BorderLayout API:
Each region may contain no more than one component,...
But having said that, as I understand your problem in greater detail, I think that your best solution is not to use JLayeredPane or to overlay two JPanels. The best solution is in fact to draw directly on the image-displaying JPanel. This is not hard to do, and shouldn't over complicate your code. For example.
You can use JLayeredPane to place one component to the top of the other. You can check this
I'm still trying to figure out BorderLayout in JavaSwing, and it's really frustrating.
I want to be able to split a pane into 3 contained sub-panels, but I'm not entirely sure how to contain it.
Here is my class Game, which contains panels ControlPanel, StatePanel, and Board (really just an extension of JPanel). I want to split the panel into those three sections like this:
Here is my code so far:
public class Game extends JPanel {
private int panespace=2;
private JPanel ControlPanel;
private JPanel StatePanel;
private Board board;
public Game()
{
setLayout(new BorderLayout(panespace, panespace));
ControlPanel=new JPanel();
ControlPanel.setLayout(new BorderLayout(panespace, panespace));
ControlPanel.setBorder(new LineBorder(Color.red, 10));
ControlPanel.setSize(100,100);
super.add(ControlPanel, BorderLayout.EAST);
StatePanel=new JPanel();
StatePanel.setLayout(new BorderLayout(panespace, panespace));
StatePanel.setBorder(new LineBorder(Color.green, 10));
StatePanel.setSize(200, 200);
super.add(StatePanel, BorderLayout.EAST);
board = new Board();
board.setLayout(new BorderLayout(panespace, panespace));
board.setBorder(new LineBorder(Color.yellow, 10));
board.setSize(300, 300);
super.add(board, BorderLayout.NORTH);
setVisible(true);
}
}
Preferably, this would use BorderLayout, but I seem to be doing it incorrectly. I've tried reading the materials that Oracle provides, but they haven't been particularly helpful. At this point, I am at the point where I want to hard code values in, but I know that I should be able to split it to have each panel take up as much of the larger Game panel as possible.
As mkhelif said, you can't have two things in the same slot. What you want is board to go into CENTER, then create another JPanel in SOUTH which contains ControlPanel and StatePanel in a FlowLayout.
You are adding ControlPanel and StatePanel on EAST both. Try adding ControlPanel on WEST.
Besides the East/East thing, you also extend JPanel instead of JFrame. ie, where you have
public class Game extends JPanel
You probably want
public class Game extends JFrame
You also set up borders, but put nothing in the panels, so the borders surround an empty space, making them look like thick lines instead of actual borders. You might try adding a JTextArea in each panel.
Also, when you change size by dragging the border, the CENTER section (which you don't use) is what grows larger. If you want the result I think you want, you'll have to use a different Layout.
Good luck!
I am using netbeans 7.0.1 to build a simple JFrame application
I am putting a textarea and a couple of buttons on using the gui builder
the buttons are on the same vertical level and the right hand button shifts right on resize of the window - that is fine but I would like the text area to do the same - i.e. resize to fit the relevant width of the window.
For the life of me I cannot see how this is done - I have looked around and I can find code for a hand coded app but not for netbeans gui builder
Update: Ah sorry, didn't read the full question, you really want to do it with netbeans.. :) Well, well, now you have this post how to do it hand-crafted aswell! :)
I wouldn't use an GUI builder for this task. It is easy to create such layout with FlowLayout and BorderLayout:
Screenshot was produced by this code:
public static void main(String... args) throws Exception {
JFrame frame = new JFrame("Test");
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
buttonPanel.add(new JButton("Hello"));
buttonPanel.add(new JButton("World!"));
frame.add(buttonPanel, BorderLayout.NORTH);
frame.add(new JTextArea("Hello World!"), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setVisible(true);
}
It's all about the layout you're using. I would personally use GridBagLayout, probably because I am accustomed to it. Basically, you should follow these steps:
Change the layout of the container which owns the textarea to GridBagLayout. You can do that by right-clicking on the container(being it the JFrame, a panel, whatever) and there you will see the Layout menu. It contains a GridBagLayout option.
In the component inspector select the JScrollPane that owns the JTextArea. Check out the "Layout" section in the properties tab. It contains the GridBagConstraints which command the layout behaviour of the JScrollPane and thus commands the JTextArea.
Play with the layout properties :). Basically you should set the X and Y weight to 1, and the Fill to "Both". This will tell the JScrollPane to fill any vertical and horizontal space there is on the Frame, and the X and Y weight will pull any other components as far as possible.
You can read more about GridBagLayout here: http://netbeans.org/kb/docs/java/gbcustomizer-basic.html
Learning GridBagLayout could take a couple of hours, getting used to it could take a couple of days, but it's worth learning. Just my 2 cents.
I'm trying to create a JDialog like the Symbol dialog in Microsoft Word that you get by choosing Symbol... from the Insert menu. Basically, it's an n x m (n and m are not known until runtime) grid of small buttons. I've got a first version of this working nicely using a GridLayout. The problem is that when you resize the dialog (and there is a requirement that you should be able to resize it), the size of the buttons changes. I need the size of the buttons to remain constant.
But I want the dimensions of the grid containing the buttons to change. For example, if the dialog gets wider, but stays the same height, the number of rows should lessen, while the number of columns increases.
I've thought of a couple of ways to fix this:
When the dialog is resized, create a new GridLayout and repopulate it with the buttons. I'm going to try this and see how it looks, but it seems like a clumsy way of doing it.
Use some other type of layout such as a FlowLayout. I took a stab at this, but it put all n x m buttons in one row. I do not want to use horizontal scroll-bars and the buttons ran off the right edge. Anyway, it's supposed to be a 2-dimensional grid of buttons.
What is the best way to solve this layout problem?
Create a buttons panel with GridLayout and set a fixed size (could be calculated at runtime of course) to it. The buttons panel should be contained in a panel of BoxLayout.
Check out the BoxLayout Tutorial
Very Very basic example:
public static void main(String[] args) throws Exception
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonPanel = new JPanel();
JPanel containerPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(2,2));
buttonPanel.add(new JButton("1"));
buttonPanel.add(new JButton("2"));
buttonPanel.add(new JButton("3"));
buttonPanel.add(new JButton("4"));
buttonPanel.setPreferredSize(new Dimension(300, 400));
containerPanel.add(buttonPanel);
frame.getContentPane().add(containerPanel);
frame.pack();
frame.setVisible(true);
}
if the dialog gets wider, but stays the same height, the number of rows should lessen, while the number of columns increases.
Wrap Layout might be what you are looking for.
I had a similar issue with a single column of buttons, and found that MiGLayout (third-party, available here) was simple and effective for this. It helped both with making a grid and with setting button sizes, although it took me a day or two to get used to its syntax.
But the key is really setting button sizes; GridLayout certainly seems like the way to go for a layout that is, well, a grid. I haven't tested, but I suspect that the built-in setXSize() methods would work just as well. The GridBagLayout tutorial has examples of some things you can do with sizing/positioning.
FlowLayout would be the way to go but you might have some configuration problems. What layout manager does the parent component use?