Scale JPanel when resizing JFrame [duplicate] - java

I have a JPanel subclass on which I add buttons, labels, tables, etc. To show on screen it I use JFrame:
MainPanel mainPanel = new MainPanel(); //JPanel subclass
JFrame mainFrame = new JFrame();
mainFrame.setTitle("main window title");
mainFrame.getContentPane().add(mainPanel);
mainFrame.setLocation(100, 100);
mainFrame.pack();
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
But when I size the window, size of panel don't change. How to make size of panel to be the same as the size of window even if it was resized?

You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.

You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager.
Simply adding the following line of code should fix your problems:
mainFrame.setLayout(new BorderLayout());
(Do this before adding components to the JFrame)

If the BorderLayout option provided by our friends doesnot work, try adding ComponentListerner to the JFrame and implement the componentResized(event) method. When the JFrame object will be resized, this method will be called. So if you write the the code to set the size of the JPanel in this method, you will achieve the intended result.
Ya, I know this 'solution' is not good but use it as a safety net.
;)

From my experience, I used GridLayout.
thePanel.setLayout(new GridLayout(a,b,c,d));
a = row number, b = column number, c = horizontal gap, d = vertical gap.
For example, if I want to create panel with:
unlimited row (set a = 0)
1 column (set b = 1)
vertical gap= 3 (set d = 3)
The code is below:
thePanel.setLayout(new GridLayout(0,1,0,3));
This method is useful when you want to add JScrollPane to your JPanel. Size of the JPanel inside JScrollPane will automatically changes when you add some components on it, so the JScrollPane will automatically reset the scroll bar.

As other posters have said, you need to change the LayoutManager being used. I always preferred using a GridLayout so your code would become:
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new GridLayout());
mainFrame.pack();
mainFrame.setVisible(true);
GridLayout seems more conceptually correct to me when you want your panel to take up the entire screen.

Related

How to Keep JCheckBox Horizontally inside JPanel

I have a JPanel. Inside Panel I have kept one JLabel and three JCheckBox.
I want to keep all the checkBox in one line after JLabel. Here is the sample code and some screenshots.
Output 1
Output 2
When i change to X_AXIS it is coming everything in one line and when i switch to Y_AXIS then it is coming new line means vertically.
But my requirement is all the checkbox should come next line means after JLabel.
JLabel should come in line and all the checkBox should come in one line.
public class CheckBoxWithJLabel {
public static void main(String[] args) {
JFrame f= new JFrame("CheckBox Example");
JPanel panel = new JPanel();
panel.setBounds(40,80,600,200);
JCheckBox chk_Embrodary=new JCheckBox("Embrodary");
JCheckBox chk_Cutting=new JCheckBox("Cutting");
JCheckBox cb_Sewing=new JCheckBox("Sewing");
panel.setLayout(new javax.swing.BoxLayout(panel, javax.swing.BoxLayout.X_AXIS));
JLabel lblHeader=new JLabel("Job Work Process Selection");
panel.add(lblHeader);
panel.add(chk_Embrodary);
panel.add(chk_Cutting);
panel.add(cb_Sewing);
f.add(panel);
f.setSize(600,400);
f.setLayout(null);
f.setVisible(true);
}
}
I want this output like
this
How to solve this problem?
I would highly suggest you to have a look through the Java Swing Tutorial, especially the Laying Out Components Within a Container section, since it seems you lack some basic understanding of how Swing and its Layout Managers are supposed to be used.
Regarding your problem:
Currently, you are using a single BoxLayout, which " puts components in a single row or column". You only want that behavior for your JCheckBoxes though, and not for your JLabel. Keeping this in mind, the solution is to split up your components and to not put all of them in a single JPanel. Doing this will grant you more flexibility in how you design your GUI, since you can use multiple layouts in different nested panels.
You could do something like this (explanation in the code comments):
public static void main(String[] args) {
JFrame f = new JFrame("CheckBox Example");
// add a Y_AXIS boxlayout to the JFrames contentpane
f.getContentPane().setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
JCheckBox cbEmbrodary = new JCheckBox("Embrodary");
JCheckBox cbCutting = new JCheckBox("Cutting");
JCheckBox cbSewing = new JCheckBox("Sewing");
// no need to set the bounds, since the layoutmanagers will determine the size
JPanel labelPanel = new JPanel(); // default layout for JPanel is the FlowLayout
JLabel lblHeader = new JLabel("Job Work Process Selection");
labelPanel.add(lblHeader); // JPanel for the label done
// JPanel for the comboboxes with BoxLayout
JPanel cbPanel = new JPanel();
cbPanel.setLayout(new BoxLayout(cbPanel, BoxLayout.X_AXIS));
cbPanel.add(cbEmbrodary);
cbPanel.add(cbCutting);
cbPanel.add(cbSewing);
f.add(labelPanel);
f.add(cbPanel);
// No need to set the size of the JFrame, since the layoutmanagers will
// determine the size after pack()
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
Output:
Sidenotes:
Don't set fixed sizes via setSize() or setBounds() to your components. Swing is designed to be used with appropariate LayoutManagers, and if you do that, calling pack() on the JFrame before setting it visible will layout the components and determine their appropriate size. (Also, don't use null-layout for the same reasons)
If you need the JLabel to not be centered but left aligned, like in your screenshot, then use the following:
FlowLayout layout = (FlowLayout) labelPanel.getLayout();
layout.setAlignment(FlowLayout.LEFT);

When i increase my GUI window size to full the components go back to standard layout

When i increase the window size to full, my components goes back to standard layout(jtable,button1,button2,button3) and so on. so i wonder if my code is right and how i can decrease the window size.
JTabbedPane jtabbed = new JTabbedPane(JTabbedPane.TOP);
JPanel panel=new JPanel();
tabellinnhold = new DefaultTableModel(defaulttabell,kolonnenavn);
posttabell = new JTable(tabellinnhold);
rullefelt = new JScrollPane(posttabell);
koble = new JButton("koble til");
lukke = new JButton("lukke");
hente = new JButton("Hente data");
avslutt = new JButton("Avslutt");
panel.add(rullefelt,BorderLayout.CENTER);
panel.add(koble,BorderLayout.SOUTH);
panel.add(lukke,BorderLayout.SOUTH);
panel.add(hente,BorderLayout.SOUTH);
panel.add(avslutt,BorderLayout.SOUTH);
//action listener
koble.addActionListener(this);
lukke.addActionListener(this);
hente.addActionListener(this);
avslutt.addActionListener(this);
jtabbed.add("se post",panel);
add(jtabbed);
//////////////////////////////////////////////////
Grensesnitt p = new Grensesnitt();
p.setDefaultCloseOperation(EXIT_ON_CLOSE);
p.GUIcode();
p.setTitle("title");
p.setSize(500,700);
p.setVisible(true);
JPanel panel=new JPanel();
...
panel.add(rullefelt,BorderLayout.CENTER);
panel.add(koble,BorderLayout.SOUTH);
panel.add(lukke,BorderLayout.SOUTH);
panel.add(hente,BorderLayout.SOUTH);
panel.add(avslutt,BorderLayout.SOUTH);
The default layout manager for a JPanel is a FlowLayout which will simply display all the components on a single line.
You can't just use the BorderLayout constraints and expect it to work.
If you want to use a BorderLayout then the code should be:
//JPanel panel=new JPanel();
JPanel panel=new JPanel( new BorderLayout() );
Also, you can't add 4 components to the "SOUTH" of the BorderLayout. You can only add a single component. So you need to create a child panel and add your components to that first:
JPanel south = new JPanel();
south.add(koble);
south.add(lukke);
south.add(hente);
south.add(avslutt);
panel.add(south, Borderlayout.SOUTH);
Read the section from the Swing tutorial on Using Layout Manager for more information and working examples to get you started.
Keep a link to the tutorial handy for examples of all Swing basics.

Position of buttons in rows, in a JPanel based 'menu bar'

I'm trying Swing programming but I can't do what I want.
I would like to place a top bar button with 2 lines of button but I just have 1 line in my case.
Here is my code:
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
setMinimumSize(new Dimension(1000,500));
setMaximumSize(new Dimension(1000,500));
JPanel panelButton = new JPanel();
JPanel panelTopButton = new JPanel();
JPanel panelBottomButton = new JPanel();
panelTopButton.add(dashboard);
panelTopButton.add(journal);
panelTopButton.add(myPlans);
panelTopButton.add(myFavorites);
panelTopButton.add(shoppingCart);
panelBottomButton.add(profile);
panelBottomButton.add(notifications);
panelButton.add(panelTopButton, BorderLayout.NORTH);
panelButton.add(panelBottomButton, BorderLayout.SOUTH);
contentPane.add(panelButton,BorderLayout.NORTH);
//Display
setSize(400,120);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
I have this
And I want this
Can somebody help me?
You need one panel for each line.
Try to do this:
JPanel panelButtonsL1 = new JPanel();
JPanel panelButtonsL2 = new JPanel();
panelButtonsL1.add(dashboard);
panelButtonsL1.add(journal);
panelButtonsL1.add(myPlans);
panelButtonsL1.add(myFavorites);
panelButtonsL1.add(shoppingCart);
panelButtonsL2.add(profile);
panelButtonsL2.add(notifications);
The default layour of JPanel is FlowLayout. Bear in mind that layout is very important to work with swing component disposition.
Define the bottom panel as GridLayout.
JPanel panelButton = new JPanel(new GridLayout(2, 1)); // 2 rows x 1 column
panelButton.add(panelButtonsL1);
panelButton.add(panelButtonsL2);
Details of GridLayout you can find on API.
You can achieve that using a GridLayout: assign a GridLayout to panelButton with two rows and one column, and then add the two panels to it.
According to what you want there is a simpler alternative by continue using the default FlowLayout from the panel. It is more appropriate than using GridLayout since you wanted the last 2 buttons to move to the next row and center itself.
If you use GridLayout, the buttons at the next row are likely going to be directly below one of the buttons above. Here are 2 ways to get what you want.
Method 1. Reduce the width of the main panel holding your buttons:
Dosing so, you will have to add the main panel using BorderLayout.CENTER.
Method 2. Add the buttons to a sub-panel of smaller width and add it to the main panel. All your buttons will be added to the smaller sub-panel:

JLabel wont change Width

I'm programming right now a Chomp Game for Uni. Everything works fine but the Label at the bottom. Its background is supposed to fill out the entire bottom. In the attachment you can see how it instead looks now. I tried setting the minimum and the preferred size of the label. The Height is changing but the width just stays adjusted to the text. How can I change that?
Note: The snippet only contains the setting up of the Frame and Panels in a custom method and not the main class.
private void init()
{
JFrame fenster = new JFrame();
this.spielfeld = new SpielfeldPanel(M, N);
this.anzeige = new SpielerAnzeigeLabel(this.spieler);
JPanel panel = new JPanel();
BoxLayout boxlayout = new BoxLayout(panel,BoxLayout.Y_AXIS);
panel.setLayout(boxlayout);
fenster.setTitle("Chomp");
fenster.setSize(1000,700);
panel.setPreferredSize(new Dimension(1000, 60));
Dimension d = new Dimension(getPreferredSize());
panel.setMinimumSize(d);
panel.add(spielfeld);
panel.add(anzeige);
fenster.add(panel);
this.spielfeld.setVisible(true);
this.anzeige.setVisible(true);
panel.setVisible(true);
fenster.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
A BoxLayout respects the width of the component to the label is displayed at its preferred width/height.
A JFrame uses a BorderLayout by default. So just add the label to the frame independently of the panel:
//panel.add(anzeige);
//fenster.add(panel);
fenster.add(panel, BorderLayout.CENTER);
fenster.add(anzeige, BorderLayout.PAGE_END);
The PAGE_END constraint respects the height but makes the width equal to the space available. Read the section from the Swing tutorial on How to Use BorderLayout for more information and examples.

java use size of JPanel to size components

Is it possible to use the size of a JPanel to set the size of components inside the JPanel? When I try to use getHeight() or getWidth() on the JPanel it always returns 0. I know that it gets it's size once the JFrame is packed, but how would one go about using the dimensions of the JPanel and applying it to a component inside it? Something like this
JPanel panel = new JPanel();
JLabel label = new JLabel();
label.setWidth(panel.getWidth());
panel.add(label);
EDIT:
See sample code below. What should I do if I want my Jlabel to be as wide as my JPanel? Is it wrong to use boxlayout in this case?
public class Main extends JFrame{
public Main(){
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.setBorder(BorderFactory.createLineBorder(Color.blue));
JLabel label = new JLabel();
label.setBorder(BorderFactory.createLineBorder(Color.red));
label.setText("label1");
label.setMinimumSize(panel.getPreferredSize());
label.setPreferredSize(panel.getPreferredSize());
panel.add(label);
add(panel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setSize(500,500);
setVisible(true);
}
public static void main(String[] args)
{
new Main();
}
}
Is it possible to use the size of a JPanel to set the size of components inside the JPanel?
This is the job of the layout manager.
When I try to use getHeight() or getWidth() on the JPanel it always returns 0
When the layout manager is invoked the Container will have a valid size so the layout manager can do its job properly.
There is no reason for you to be playing with sizes. Leave it to the layout managers to do their jobs.
Update:
What should I do if I want my Jlabel to be as wide as my JPanel? Is it wrong to use boxlayout in this case?
The BoxLayout attempts to respect the minimum/maximum size of the component. In you case you should be able to do something like:
JLabel label new JLabel("some text");
label.setBorder(....);
Dimension d = label.getPreferredSize();
d.width = 32767;
label.setMaximumSize( d );
Or maybe a simpler approach is to start with a BorderLayout. You can add the label to the NORTH. Then create another panel and add it to the CENTER.
Of course you can, but be careful that the result depends on the layout manager of your JPanel and on the number of its child components.
Setting the width ignores resizing. LayoutManagers typically ask components for their preferred widths and heights, and expand / contract items to maintain a visually appealing position after the frame has been resized. So, your best option is to leverage the layout manager and report a "preferred width".
You can use setPreferredWidth(...); but, if your preferred width is to change over the run of the program (due to window size changes), you will need to listen to the panel in question and update your button's preferred width as the panel's preferred width changes (this assumes it changes, which might not be true).

Categories

Resources