Here is my JPanel class. I have BoxLayout in it and only one JLabel added. My JLabel is on the left side of the screen. Is there any way to align all the components that are in the BoxLayout to the center. I tried this : setAlignmentX(CENTER_ALIGNMENT); but it doesnt work
public class MainPanel extends JPanel
{
// This layout we will use as our base layout.
private BoxLayout mainLayout = new BoxLayout(this, BoxLayout.Y_AXIS);
// This we will use to control padding in our main panel
EmptyBorder mainBorder = new EmptyBorder(10, 10, 10, 10);
private JLabel title = new JLabel("Podesavanja");
public MainPanel()
{
setLayout(mainLayout);
setBackground(Color.GRAY);
setAlignmentY(CENTER_ALIGNMENT);
// Setting padding
setBorder(mainBorder);
add(title);
}
// Dodajemo sve Ostale panele u ovu main panelu
public static void addPanel(JPanel panel)
{
addPanel(panel);
}
}
First of all, you call setAlignmentY() instead of setAlignmentX(). Second, you're calling it on the panel instead of calling it on the JLabel.
Fix those two bugs, and the label will be centered.
Is there any way to do it for all the elements inside layout ?
Not with a BoxLayout. A BoxLayout uses the alignment of individual components.
You can use different layout managers:
A GridBagLayout will allow you to set the alignment by using a GridBagConstraint. You set the alignment once and it will be used by all components. Of course you need to set the gridY of each component. So is this any different then setting the x alignment of the BoxLayout?
You can use a 3rd part layout manager like the the Relative Layout.
It works similar to a BoxLayout in that you can layout components horizontally or vertically. However RelativeLayout also allows you to specify alignment for the panel as a whole:
RelativeLayout rl = new RelativeLayout(RelativeLayout.Y_AXIS);
rl.setAlignment( RelativeLayout.CENTER );
JPanel panel = new JPanel( rl );
Related
I'm trying to put multiple JPanel cards into my main panel. and if new card panel does not fit I want it to be placed in next line. In the image below, you see that all my card panels go to right and if I set HORIZONTAL_SCROLLBAR_ALWAYS horizontal scroll works. So here I want 4 card panel in each line of my main panel so that vertical scroll works.
public class PanelTraining extends JPanel{
private static final long serialVersionUID = 1L;
public PanelTraining(List<FccMeta> ffcms) {
super(new BorderLayout()); // set layout to absolute
setPreferredSize(new Dimension(880, 580));
setBorder(new LineBorder(Color.decode("#A11E1E"),1, true));
JPanel pnlChart = new JPanel();
pnlChart.setPreferredSize(new Dimension(860, 180));
pnlChart.setBackground(Color.YELLOW);
add(pnlChart, BorderLayout.NORTH);
JPanel pnlTrSet = new JPanel(new FlowLayout(FlowLayout.LEADING, 5, 5));
//pnlTrSet.setSize(860, 380);
for (FccMeta fccMeta : ffcms) {
JPanel pnlCard = new MyCustomPanelCard();
pnlTrSet.add(pnlCard);
}
JScrollPane scroll = new JScrollPane(pnlTrSet);
//scroll.setPreferredSize(new Dimension(860, 380));
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(scroll, BorderLayout.CENTER);
}
}
EDIT according to the answer given below. I changed my implementation by this Class
ScrollablePanel pnlTrSet = new ScrollablePanel(new FlowLayout());
pnlTrSet.setScrollableWidth( ScrollablePanel.ScrollableSizeHint.FIT );
pnlTrSet.setScrollableBlockIncrement(
ScrollablePanel.VERTICAL, ScrollablePanel.IncrementType.PIXELS, 230);
You need to implement the Scrollable interface of your panel to have the width fixed to the size of the viewport of the scrollpane.
Basically you need to override the getScrollableTracksViewportWidth() method to return “true”.
An easy way to do this is to use the Scrollable Panel. It has a method that allows you to control this property.
Edit:
The above will only prevent the horizontal scrollbar from appearing. However the FlowLayout will continue to display all the buttons on a single row because the preferred size calculation of the panel is still not correct.
To get the buttons to wrap, you must replace the FlowLayout of your panel with the Wrap Layout. The Wrap Layout will recalculate the preferred height of the panel correctly so that the components can wrap and the vertical scrollbar can appear.
import java.awt.*;
import javax.swing.*;
public class JFrameGUI extends JFrame
{
JLabel item1;
public JFrameGUI(int l, int b , String Title)
{
setTitle(Title);
setLayout(new FlowLayout());
setSize(l, b);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
item1 = new JLabel("This is a Sentence.");
item1.setToolTipText("This is gonna show up on hover.");
add(item1);
}
public static void main(String[] args)
{
JFrameGUI g = new JFrameGUI(1280,720,"The End Of The Line");
JPanel p = new JPanel();
p.setBackground(Color.BLUE);
g.add(p);
}
}
When I execute this , all i get is a tiny Blue square nest to the "This is a sentence" string . I've tried everything !
You need to set the layout of the frame to a layout that doesn't respect the preferred sizes of its children. FlowLayout does, and your JPanel has no preferred size without any components added to it, or specifying a preferred size.
A simple fix, set the layout of the frame to BorderLayout, or not set a layout at all, since JFrame already has a default BorderLayout. Note though that you probably want to add the JLabel to the JPanel and not the JFrame. Unless you do want to add it the JFrame and not the background JPanel, you need to specify a BorderLayout position for the one you don't want in the center.
You can see this answer to see which layout managers respect preferred sizes and which don't
See more at Layout out Components Withing a Container
Also, setVisible(true) shoul be the last thing you do after adding all components.
I want to add a status bar to my panel.
Actually, it looks like this:
But I want the text to be displayed in the left lower corner.
Here is my code:
private JPanel pnl1, pnl2;
//pnl1 contains everything exept the status bar, pnl2 only status bar
private JLabel lab3;
//lab3 is the status bar
(…)
public static void main(String[] args) {
new Panel1();
}
public Panel1() {
pnl1 = new JPanel();
pnl2 = new JPanel();
lab3 = new JLabel("Started."); //Statusbar
(…)
pnl1.setLayout(new FormLayout(
"40*($lcgap, 10dlu)",
"30*($lgap, 10dlu)"
));
CellConstraints cc = new CellConstraints();
pnl1.add(…)
pnl2.add(lab3);
this.add(pnl1);
this.add(pnl2, BorderLayout.PAGE_END);
this.(…)
Thank you for your help!
You are adding the label into pnl2 without, it seems, changing the layout. The default layout for JPanel is FlowLayout, which uses a centered alignment.
If you want the label to be aligned to the left, you can use a FlowLayout, making sure the alignment is set to LEADING:
pnl2.setLayout(new FlowLayout(FlowLayout.LEADING));
pnl2.add(lab3);
Or you can use a different layout, for instance BorderLayout:
pnl2.setLayout(new BorderLayout());
pnl2.add(lab3);
I have a bar at the top of my application that has a number of buttons either side of a JLabel. The button's visibility is dependent upon the current task a user is carrying out and one of the button's text may also change depending on the current state.
What I would like to do is have a number of buttons stick to the left of the JPanel, the JLabel's center to be in the very center of the JPanel and the rest of the buttons to be to the right of the JPanel.
So far I have managed to get the buttons sticking to the left and the right using various methods and layout managers but I cannot get the JLabel's center to be in the dead center of the JPanel. The best I have managed to get is the label near enough to the center but it would then move around as the buttons are set to visible or their text changes.
Is it possible to force the JLabel to remain dead center?
Note: the buttons will never become big enough to meet either edge of the JLabel, so that is not a problem.
You could also use a BoxLayout, with X_AXIS layout, and add to the container
Edit: Here's an example
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(Box.createHorizontalGlue());
panel.add(innerPanel);
panel.add(Box.createHorizontalGlue());
As I see it you need the label to be displayed at its preferred size and then you need a left and right panel to equally fill the remaining space available in the window.
You can use the Relative Layout class.
import java.awt.*;
import javax.swing.*;
public class RelativeSSCCE extends JPanel
{
public RelativeSSCCE()
{
JPanel left = new JPanel( new FlowLayout(FlowLayout.LEFT) );
left.add( new JButton("L1") );
left.add( new JButton("L2") );
left.add( new JButton("L3") );
JLabel center = new JLabel("Centered");
JPanel right = new JPanel( new FlowLayout(FlowLayout.RIGHT) );
right.add( new JButton("Right1") );
right.add( new JButton("Right2") );
right.add( new JButton("Right3") );
// choose your layout manager here
setLayout( new RelativeLayout() );
Float ratio = new Float(1);
add(left, ratio);
add(center);
add(right, ratio);
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Basic RelativeSSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new RelativeSSCCE() );
frame.setSize(600, 100);
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Use BorderLayout. Add the JLabel with the BorderLayout.CENTER constraint and add a pair of JPanels with the BorderLayout.EAST and BorderLayout.WEST constraints. Add your additional buttons to the appropriate JPanel.
To have the text appear centered, you also need to set the Label's horizontalAlignment to JLabel.CENTER.
setAlignmentX(java.awt.Component.CENTER_ALIGNMENT)
and
setAlignmentY(java.awt.Component.CENTER_ALIGNMENT)
may help if used with the elements which have to be centered, e.g. JPanel
may be I`m necroposting, but setAlignmentX(java.awt.Component.CENTER_ALIGNMENT) and setAlignmentY(java.awt.Component.CENTER_ALIGNMENT) may help...
I have problem while setting the Jlabel location.
I set the content pane to some JPanel, I created and tried to add my JLabel.
JLabel mainTitle = new JLabel("SomeApp");
mainTitle.setFont(new Font("Arial",2 , 28));
mainTitle.setBounds(0,0, 115, 130);
getContentPane().add(mainTitle);
I want that my JPanel will be on the top left corner on my application and what I am getting is "SomeApp" on the top center.(and not top left).
btw I tried to add JButton the and the I can`t change the width,height,x,y of the JButton.
Swing uses Layout Managers to place the components.
You have to understand how they work to use them effectively. You can set the layout manager to null, and do the layout your self, but is not recommendable because you'll have to keep track of new components each time, and perform layout computation your self when the window moves shrink etc.
Layout managers are a bit hard to grasp at first.
Your windows could be like this:
Using this code:
import javax.swing.*;
import java.awt.Font;
import java.awt.FlowLayout;
class JLabelLocation {
public static void main( String [] args ) {
JLabel mainTitle = new JLabel("SomeApp");
mainTitle.setFont(new Font("Arial",2 , 28));
//mainTitle.setBounds(0,0, 115, 130); //let the layout do the work
JFrame frame = new JFrame();
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));// places at the left
panel.add( mainTitle );
frame.add( panel );// no need to call getContentPane
frame.pack();
frame.setVisible( true );
}
}
Where a particular widget ends up in its container depends on the layout manager that it's using. The layout manager determines how to resize and arrange the widgets to make them fit appropriately. Obviously, the default layout for the content pane decided that the top center was the best place to put the JLabel.
If you want to get to not use a layout manager and just place everything yourself (which generally isn't the best way to lay things out btw), then add:
getContentPane().setLayout(null);
Using layouts is usually a better idea since they allow for dynamic resizing of components. Here's how you'd do it with a BorderLayout:
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add (new JLabel ("Main title"), BorderLayout.NORTH);
If you want to add something to the right of the label you could create an additionnal panel with it's own layout :
// Create a panel at the top for the title and anything else you might need
JPanel titlePanel = new JPanel (new BorderLayout());
titlePanel.add(new JLabel ("Main title"), BorderLayout.WEST);
// Add the title panel to the frame
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(titlePanel, BorderLayout.CENTER);
Here are some usefull links to get started with layouts:
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/visual.html
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/using.html