I want my Game to look like this:
but it wont and I don't know why.. everything just doesn't go in the places I want it to be.
Could someone help me? What am I doing wrong?
It looks like this:
The color-changing isn't the problem.. its just where all the stuff is located.
package view;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WelcomeScreen extends JFrame{
JButton button;
JLabel label;
ActionListener action;
GridBagLayout gb = new GridBagLayout();
public <button> WelcomeScreen(ActionListener action){
JPanel panel = new JPanel();
this.setSize(800,600);
GridBagConstraints gcon = new GridBagConstraints();
gcon.weightx = 1;
gcon.weighty = 1;
gcon.fill = GridBagConstraints.HORIZONTAL;
gcon.insets = new Insets(5,5,5,5);
button = new JButton("Start");
button.setPreferredSize(new Dimension(200, 50));
button.setFont(new Font("Arial", Font.PLAIN, 20 ));
button.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 2));
button.setHorizontalAlignment(SwingConstants.LEFT);
label = new JLabel("Game");
label.setPreferredSize(new Dimension(200, 50));
label.setFont(new Font("Arial", Font.PLAIN, 60 ));
this.action = action;
panel.setBorder(BorderFactory.createEmptyBorder(20, 10, 20, 10));
panel.setLayout(gb);
//label
gcon.gridx = 2;
gcon.gridy = 0;
//gcon.gridwidth = 4;
//gcon.gridheight = 1;
gb.setConstraints(label,gcon);
panel.add(label);
//button
gcon.gridx = 2;
gcon.gridy = 1;
//gcon.gridwidth = 2;
//gcon.gridheight = 1;
gb.setConstraints(button,gcon);
panel.add(button);
this.add(panel,BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Start");
this.setVisible(true);
button.addActionListener(action);
}
}
As I understand you want the label and the button to be centered in the frame.
For this purpose do not set weightx and weighty since they will tell to layout manager to expand to the available space.
So remove
gcon.weightx = 1;
gcon.weighty = 1;
then, replace the following code
//label
gcon.gridx = 2;
gcon.gridy = 0;
//gcon.gridwidth = 4;
//gcon.gridheight = 1;
gb.setConstraints(label,gcon);
panel.add(label);
//button
gcon.gridx = 2;
gcon.gridy = 1;
//gcon.gridwidth = 2;
//gcon.gridheight = 1;
gb.setConstraints(button,gcon);
panel.add(button);
with this
//label
gcon.gridx = 0;
gcon.gridy = 0;
panel.add(label, gcon);
//button
gcon.gridx = 0;
gcon.gridy = 1;
panel.add(button, gcon);
Since no row and column has weight greater than 0 the layout manager will automatically place the label-button block in the middle.
Complete code
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class WelcomeScreen extends JFrame{
JButton button;
JLabel label;
ActionListener action;
GridBagLayout gb = new GridBagLayout();
public <button> WelcomeScreen(ActionListener action){
JPanel panel = new JPanel();
this.setSize(800,600);
GridBagConstraints gcon = new GridBagConstraints();
gcon.fill = GridBagConstraints.HORIZONTAL;
gcon.insets = new Insets(5,5,5,5);
button = new JButton("Start");
button.setPreferredSize(new Dimension(200, 50));
button.setFont(new Font("Arial", Font.PLAIN, 20 ));
button.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 2));
button.setHorizontalAlignment(SwingConstants.CENTER);
label = new JLabel("Game");
label.setPreferredSize(new Dimension(200, 50));
label.setFont(new Font("Arial", Font.PLAIN, 60 ));
this.action = action;
panel.setBorder(BorderFactory.createEmptyBorder(20, 10, 20, 10));
panel.setLayout(gb);
//label
gcon.gridx = 0;
gcon.gridy = 0;
panel.add(label, gcon);
//button
gcon.gridx = 0;
gcon.gridy = 1;
panel.add(button, gcon);
this.add(panel,BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Start");
this.setVisible(true);
button.addActionListener(action);
}
public static void main(String[] args) {
new WelcomeScreen(null).setVisible(true);
}
}
If you're willing to use Libraries I can recommend MigLayout.
Solution:
With MigLayout the code looks a bit more readable and it's generally easier:
JPanel contentPane = new JPanel(new MigLayout("", "[grow, center]", "[grow, center]"));
JPanel panel = new JPanel(new MigLayout("wrap 1", "[grow, fill]", "[]20px[]"));
JLabel label = new JLabel("Game");
label.setFont(new Font("Arial", Font.PLAIN, 60 ));
panel.add(label);
JButton button = new JButton("Start");
button.setFont(new Font("Arial", Font.PLAIN, 20 ));
button.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 2));
button.setHorizontalAlignment(SwingConstants.LEFT);
panel.add(button);
contentPane.add(panel);
setContentPane(contentPane);
Explanation:
The 'panel' is still the JPanel holding the components. The content is controlled by the layouts contraints:
The first argument of its MigLayout are the layout contrains and in that case it just auto wraps to the next line after each added component.
The second argument are the column contraints. Here it makes sure that the 'cells' (the layout manager works like a table) expand with 'grow' and the component inside that cell fill the whole cell with 'fill'.
The third argument are the row constraints. Here they just defines the gap between the rows. The '[]' in the column & row contrains stand for a column / row respectively. Anything inside that bracket defines how the cell and its content behaves, anything outside the brackets is used for defining gaps.
The 'contentPane' just makes sure that the 'panel' is centered inside using the same methods described above. It can then be added to a bigger component (like a frame) and expand, still keeping the content centered.
You should find all the info abould the Layouts capabilities at http://www.miglayout.com/whitepaper.html
Related
public class AFS {
public JPanel afs(final Fields input){
JPanel titlePanel = new JPanel();
//Title fields
JLabel afs = new JLabel("Statement", Label.LEFT);
Label mm = new Label("month ", Label.LEFT);
Label my = new Label("Year ", Label.LEFT);
//first line
titlePanel.add(afs);
titlePanel.add(mm);
titlePanel.add(input.MENTRY);
titlePanel.add(my);
titlePanel.add(input.YENTRY);
titlePanel.setPreferredSize(null);
//Left Panels
JPanel sb = new JPanel();
JPanel entry = new JPanel();
entry.setLayout(new BoxLayout(entry, BoxLayout.Y_AXIS));
entry.setAlignmentX(Component.LEFT_ALIGNMENT);
entry.add(new Label("Service "));
entry.add(input.s);
entry.add(new Label("Amount "));
entry.add(input.a);
entry.add(new Label("Counter "));
entry.add(input.o);
entry.add(new Label("Division "));
entry.add(input.d);
sb.add(entry);
JPanel holderPanel = new JPanel();
holderPanel.setLayout(new BoxLayout(holderPanel, BoxLayout.Y_AXIS));
holderPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
holderPanel.add(titlePanel);
holderPanel.add(sb);
JButton start = new JButton("Save Current");
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ScriptAction action = new ScriptAction();
action.saveAll(input,1);
}
});
holderPanel.add(start);
return holderPanel;
}
I have a short version of what looks like above code.
The current layout looks like this:
But I want the layout look like (paint edited).
I have tried swap using gridLayout for the entry and it will display 2 rows but gridlayout will still align everything in the center (include the title and the header). Furthermore the button span would be across the entire bottom section. I was wondering if there are any suggested way to do this?
You would need to use a combination of layout managers to achieve the desired output:
Before resize / After resize
In this case there are 3 main parts:
Top pane (Uses Box to align some text on the left and some on the right)
Middle pane (Uses GridBagLayout to position the components as in the image, maybe GridLayout with proper insets might work as well)
Bottom pane (Uses default JPanel's layout: FlowLayout)
The top pane uses 2 JPanels as well, the first one for the label Statement alone and other with FlowLayout aligned to the right for the other 4 components, as per this answer BoxLayout does not respect the preferred size of our JTextFields. So a workaround is to wrap them inside another JPanel and then wrap that JPanel along with the Statement label.
A similar problem arises with the middle pane, which needs to use 2 JPanels: One for the fields wrapped inside another bigger one which holds it and the JButton at the bottom (Save Current). We could achieve a similar output by adding the JButton with a gridx = 2 and gridy = 2 with the counter and division label and fields on gridx = 3 and gridx = 4 respectively (instead of 2 & 3) but we would then need to add gbc.insets to add insets to the top and bottom with high values as well... It's up to you which one to use :)
The code that produces the above outputs is the following:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class FormSample {
private JFrame frame;
private JPanel topRightPane;
private JPanel centerPane;
private JPanel centerWithButtonPane;
private JPanel buttonsPane;
private JTextField monthField;
private JTextField yearField;
private JTextField serviceField;
private JTextField amountField;
private JTextField counterField;
private JTextField divisionField;
private static final int LEFT_MARGIN = 50; //Increase / Decrease to add extra space between components
private static final int RIGHT_MARGIN = LEFT_MARGIN;
//Change insets accordingly to add extra space between components (top, left, bottom, right)
private static final Insets leftInsets = new Insets(0, LEFT_MARGIN, 0, 0);
private static final Insets rightInsets = new Insets(0, 0, 0, RIGHT_MARGIN);
private static final Insets defaultInsets = new Insets(0, 0, 0, 0);
private JButton saveCurrentButton;
private JButton saveAllButton;
private JButton resetButton;
public static void main(String[] args) {
SwingUtilities.invokeLater(new FormSample()::createAndShowGui);
}
private void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
monthField = new JTextField(10);
yearField = new JTextField(10);
serviceField = new JTextField(10);
amountField = new JTextField(10);
counterField = new JTextField(10);
divisionField = new JTextField(10);
saveCurrentButton = new JButton("Save Current");
saveAllButton = new JButton("Save all");
resetButton = new JButton("Reset");
buttonsPane = new JPanel();
topRightPane = new JPanel();
topRightPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
topRightPane.add(new JLabel("Month"));
topRightPane.add(monthField);
topRightPane.add(new JLabel("Year"));
topRightPane.add(yearField);
centerWithButtonPane = new JPanel();
centerWithButtonPane.setLayout(new BoxLayout(centerWithButtonPane, BoxLayout.PAGE_AXIS));
Box box = Box.createHorizontalBox();
box.add(new JLabel("Statement"));
box.add(Box.createHorizontalGlue());
box.add(topRightPane);
centerPane = new JPanel();
centerPane.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = defaultInsets;
centerPane.add(new JLabel("Service"), gbc);
gbc.gridx = 1;
gbc.insets = rightInsets;
centerPane.add(serviceField, gbc);
gbc.gridx = 2;
gbc.insets = leftInsets;
centerPane.add(new JLabel("Counter"), gbc);
gbc.gridx = 3;
gbc.insets = defaultInsets;
centerPane.add(counterField, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = defaultInsets;
centerPane.add(new JLabel("Amount"), gbc);
gbc.gridx = 1;
gbc.insets = rightInsets;
centerPane.add(amountField, gbc);
gbc.gridx = 2;
gbc.insets = leftInsets;
centerPane.add(new JLabel("Division"), gbc);
gbc.gridx = 3;
gbc.insets = defaultInsets;
centerPane.add(divisionField, gbc);
saveCurrentButton.setAlignmentX(Component.CENTER_ALIGNMENT); //Force centered alignment for our JButton
centerWithButtonPane.add(centerPane);
centerWithButtonPane.add(saveCurrentButton);
buttonsPane.add(saveAllButton);
buttonsPane.add(resetButton);
frame.add(box, BorderLayout.NORTH);
frame.add(centerWithButtonPane, BorderLayout.CENTER);
frame.add(buttonsPane, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Also please follow the advices given by #SergiyMedvynskyy about not mixing AWT and Swing components (i.e. JTextField with TextField) and only use Swing components as AWT ones are buggy.
I have a two jpanels: jpanel1 and jpanel2 which must have correct minimal size according to their content. jpanel0 is the container for these two panels, it must be on the left side of a frame. And here is jpanel3 that should take the rest of the available space on the right side.
How to set the size of a jpanel to all available space?
My desired output:
My current output:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class Panels {
public static void main(String[] args) {
JFrame myFrame = new JFrame();
myFrame.setLayout(new BorderLayout());
JTabbedPane jtp = new JTabbedPane();
JPanel jPaneTab1 = new JPanel();
jPaneTab1.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel jpanel0 = new JPanel();
jpanel0.setLayout(new BoxLayout(jpanel0, BoxLayout.Y_AXIS));
jpanel0.setBorder(BorderFactory.createTitledBorder("jpanel0"));
jpanel0.setBackground(Color.RED);
JPanel jpanel1 = new JPanel();
jpanel1.setLayout(new GridBagLayout());
jpanel1.setBorder(BorderFactory.createTitledBorder("jpanel1"));
GridBagConstraints gc = new GridBagConstraints();
jpanel1.setBackground(Color.BLUE);
JLabel jlabel1 = new JLabel("jlabel1");
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.insets = new Insets(0, 0, 0, 2);
jpanel1.add(jlabel1, gc);
JLabel jlabel2 = new JLabel("jlabel2");
gc.gridx = 0;
gc.gridy = 1;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.insets = new Insets(0, 0, 0, 2);
jpanel1.add(jlabel2, gc);
JPanel jpanel2 = new JPanel();
jpanel2.setLayout(new GridBagLayout());
jpanel2.setBorder(BorderFactory.createTitledBorder("jpanel2"));
GridBagConstraints gc2 = new GridBagConstraints();
jpanel1.setBackground(Color.BLUE);
JLabel jlabel3 = new JLabel("jlabel3");
gc2.gridx = 0;
gc2.gridy = 0;
gc2.anchor = GridBagConstraints.NORTHWEST;
gc2.insets = new Insets(0, 0, 0, 2);
jpanel2.add(jlabel3, gc2);
JLabel jlabel4 = new JLabel("jlabel4");
gc2.gridx = 0;
gc2.gridy = 1;
gc2.anchor = GridBagConstraints.NORTHWEST;
gc2.insets = new Insets(0, 0, 0, 2);
jpanel2.add(jlabel4, gc2);
JPanel jpanel3 = new JPanel();
jpanel3.setBackground(Color.YELLOW);
JLabel jlabel5 = new JLabel("jpanel3");
jpanel3.add(jlabel5);
jpanel0.add(jpanel1);
jpanel0.add(jpanel2);
jPaneTab1.add(jpanel0, BorderLayout.WEST);
jPaneTab1.add(jpanel3, BorderLayout.CENTER);
JPanel jPaneTab2 = new JPanel();
jtp.addTab("tab1", jPaneTab1);
jtp.addTab("tab2", jPaneTab2);
myFrame.add(jtp);
myFrame.setSize(800, 600);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
Addition:
When I use BorderLayout for main(tab panel) I'm getting another problem:
Layouts work easier when you break down the layout into logical panels and then nest panels with different layout managers.
For example, use a panel with a BorderLayout as the content for the tabbed pane.
Then you create a "ride side panel" and add it to this panel and a "center panel"
JPanel main = new JPanel( new BorderLayout() );
JPanel rightSide = new JPanel( ... );
JPanel center = new JPanel(...);
main.add(rightSide, BorderLayout.LINE_START);
main.add(center, BorderLayout.CENTER);
Then you set the layouts for the "rightSide" and "center" panels and add components to each of those panels.
You should not be using GridBagLayout, BorderLayout, or BoxLayout managers. These are outdated managers from the 90s.
For instance, when you do this:
gc.insets = new Insets(0, 0, 0, 2);
you are hardcoding pixel-width spaces between components, which
will not work across the wide variety of today's screens.
Insted, one should choose either GroupLayout or MigLayout.
Here is a working example with the MigLayout manager. Notice how easy
is to create the layout with this manager. (Four lines of code.) Also, we use logical pixels (lp) instead of physical pixels.
package com.zetcode;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import net.miginfocom.swing.MigLayout;
public class PanelsEx extends JFrame {
public PanelsEx() {
initUI();
}
private void initUI() {
JTabbedPane tabpane = new JTabbedPane();
JPanel mainPanel = new JPanel();
JPanel pnl1 = createPanel("Panel 1");
JPanel pnl2 = createPanel("Panel 2");
JPanel pnl3 = createPanel("Panel 3");
mainPanel.setLayout(new MigLayout("ins 10lp"));
mainPanel.add(pnl1, "w 150lp, h 100lp, split 2, flowy, ay top");
mainPanel.add(pnl2, "w 150lp, h 100lp");
mainPanel.add(pnl3, "push, grow");
tabpane.add("First", mainPanel);
add(tabpane);
pack();
setTitle("Panels");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private JPanel createPanel(String text) {
JLabel lbl = new JLabel(text);
JPanel pnl = new JPanel();
pnl.add(lbl);
pnl.setBorder(BorderFactory.createEtchedBorder());
return pnl;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
PanelsEx ex = new PanelsEx();
ex.setVisible(true);
});
}
}
And here is a screenshot:
Okay, so I need your help guys. I don't know what I missed but the insets and anchor is not taking effect even though I've set the layout to GridBag.
I need to put the logout button just above the tabbedpane and position the logout button on the upper right hand corner. In other words, tabbed pane on position gridx = 0, gridy = 1; and logout Button on position gridx = 0, gridy = 0;
Also, the myaccount button, leftpanel and rightpanel which are inside the home panel, won't get the insets i applied.
What am I missing. Please help because I'm new to this layout.
TopPanel.java
package MainComponents;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.border.Border;
import MainTab_TabbedPane.TopTabbedPane;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
public class TopPanel extends JPanel {
//DECLARATION
JButton logOutButton = new JButton("Logout");
TopTabbedPane topTabbedPane = new TopTabbedPane();
private final Border myLineBorder = BorderFactory.createLineBorder(Color.BLACK, 2);
//CONSTRUCTOR
public TopPanel(){
setPanelInitialProperties();
addComponents();
}
//METHODS
private void setPanelInitialProperties(){
setLayout(new GridBagLayout());
setBorder(myLineBorder); //sets a Line Border for this panel
}
private void addComponents(){
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
this.add(topTabbedPane); //adds TabbedPane holding Home, Administration... to this Top Panel
gbc.gridx = 0;
gbc.gridy = 0;
this.add(logOutButton);
}
}
HomeTopPanel.java
package HomeTab;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class HomeTopPanel extends JPanel {
private final JButton MyAccountButton = new JButton("My Account");
private final JPanel leftPanel = new JPanel(new GridBagLayout());
private final JPanel rightPanel = new JPanel(new GridBagLayout());
private final Border leftPanelLineBorder = BorderFactory.createLineBorder(Color.BLACK, 2);
private final Border rightPanelLineBorder = BorderFactory.createLineBorder(Color.BLACK, 2);
//CONSTRUCTOR
public HomeTopPanel(){
constructMyAccountButton();
constructPanels();
setLeftRightPanelBorders();
this.setLayout(new GridBagLayout());
}
private void constructMyAccountButton(){
GridBagConstraints MyAccountButton_gbc = new GridBagConstraints();
MyAccountButton_gbc.gridx = 0; MyAccountButton_gbc.gridy = 0;
MyAccountButton_gbc.anchor = GridBagConstraints.NORTHWEST;
this.add(MyAccountButton);
}
private void constructPanels(){
GridBagConstraints leftPanelgbc = new GridBagConstraints();
GridBagConstraints rightPanelgbc = new GridBagConstraints();
leftPanelgbc.insets = new Insets(3,3,3,3);
leftPanelgbc.gridx = 1; leftPanelgbc.gridy = 0;
leftPanel.setPreferredSize(new Dimension(300, 500));
this.add(leftPanel);
rightPanelgbc.insets = new Insets(3,3,3,3);
rightPanelgbc.gridx = 2; leftPanelgbc.gridy = 0;
rightPanel.setPreferredSize(new Dimension(300, 500));
this.add(rightPanel);
}
private void setLeftRightPanelBorders(){
leftPanel.setBorder(leftPanelLineBorder);
rightPanel.setBorder(rightPanelLineBorder);
this.setBorder(leftPanelLineBorder);
}
}
Thanks in advanced. I'm sure there's something I missed but I don't know.
INSETS won't apply. =( ??
UPDATE:
I added the insets with the following code:
private void constructPanels(){
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.gridx = 1; gbc2.gridy = 0;
gbc2.insets = new Insets(5, 5, 5, 5);
leftPanel.setPreferredSize(new Dimension(250, 300));
this.add(leftPanel,gbc2);
gbc2.gridx = 2; gbc2.gridy = 0;
gbc2.insets = new Insets(5, 5, 5, 5);
rightPanel.setPreferredSize(new Dimension(300, 500));
this.add(rightPanel,gbc2);
}
but still not getting any inset of 5.
Apply the constraints when adding components
add(topTabbedPane, gbc);
GridBagConstraints MyAccountButton_gbc = new GridBagConstraints();
Variable names should NOT start with an upper case character. Most of your other names are correct. Then is no reason to be sloppy. Follow the Java conventions.
constructMyAccountButton();
constructPanels();
setLeftRightPanelBorders();
this.setLayout(new GridBagLayout());
The layout must be set BEFORE you add components to the panel.
GridBagConstraints MyAccountButton_gbc = new GridBagConstraints();
MyAccountButton_gbc.gridx = 0; MyAccountButton_gbc.gridy = 0;
MyAccountButton_gbc.anchor = GridBagConstraints.NORTHWEST;
//this.add(MyAccountButton); // where is the constraint?
this.add(MyAccountButton, myAccountButton_gbc);
You actually have to use the constraint.
I'm having a problem with vertical filling in my GridBagLayout-GUI. Here is the Code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class Spielklasse {
public static void main(String[] args) {
JPanel page = new JPanel();
page.setLayout(new GridBagLayout());
for (int i = 0; i < 5; i++) {
JPanel subPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel();
label.setText("label " + i + ":");
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(120,20));
subPanel.add(label, BorderLayout.WEST);
subPanel.add(textField, BorderLayout.EAST);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.NORTHWEST;
c.gridx = 1;
c.gridy = i;
c.weightx = 1;
c.weighty = 1;
c.insets = new Insets(10, 20, 10, 20);
c.fill = GridBagConstraints.HORIZONTAL;
page.add(subPanel, c);
}
JScrollPane scrollPane = new JScrollPane(page);
JFrame frame = new JFrame();
frame.setSize(300,500);
frame.add(scrollPane);
frame.setVisible(true);
}
}
I want to have label+textfield directly under the previous ones without filling the vertical space between (like when you resize my example vertically till you can see the vertical scrollbar). How can I achieve that? With my code the whole panel is filled vertically, but I don't want this.
Remove next line c.weighty = 1;.
Read more in docs.
Edit: use dummy JLabel for grabbing free space, after loop:
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 5;
c.fill = GridBagConstraints.BOTH;
c.weightx=1;
c.weighty=1;
c.gridwidth = 2;
page.add(new JLabel(" "),c);
I made a few changes to your code.
Always start a Swing application with a call to the SwingUtilities invokeLater method. This puts the Swing components on the Event Dispatch thread.
Since you're using the GridBagLayout, you can lay out your labels and text fields directly on the page JPanel.
I created a GridBagConstraints for each label and text field. That way, we're not relying on defaults. We specify the correct anchor and fill values for each component.
I added a couple of missing JFrame methods. You either have to specify a default close operation, or you have to close the application yourself. Without this specification, your application will continue to run after you close the main JFrame.
Edited to add:
To get the effect you want, put your page JPanel inside another JPanel. The outside JPanel has the FlowLayout.
Here's the modified code.
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Spielklasse implements Runnable {
private static final Insets baseInsets =
new Insets(10, 20, 10, 20);
#Override
public void run() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout());
JPanel page = new JPanel();
page.setLayout(new GridBagLayout());
int gridy = 0;
for (int i = 0; i < 5; i++) {
JLabel label = new JLabel();
label.setText("Label " + i + ":");
addComponent(page, label, 0, gridy,
1, 1, baseInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
JTextField textField = new JTextField(20);
addComponent(page, textField, 1, gridy++,
1, 1, baseInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
}
mainPanel.add(page);
JScrollPane scrollPane = new JScrollPane(mainPanel);
JFrame frame = new JFrame("Spielklasse");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
private void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight,
Insets insets, int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor,
fill, insets, 0, 0);
container.add(component, gbc);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Spielklasse());
}
}
I am working on java swing application and I am adding components dynamically in a JPanel. I want to set a JScrollPane on this panel and only if the panel is full we can see this scrollpane.
How can I do it on this :
package add_button;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
public class MyExample
{
// Field members
static JPanel panel = new JPanel();
static Integer indexer = 1;
static List<JLabel> listOfLabels = new ArrayList<JLabel>();
static List<JTextField> listOfTextFields = new ArrayList<JTextField>();
public static void main(String[] args)
{
// Construct frame
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
frame.setPreferredSize(new Dimension(990, 990));
frame.setTitle("My Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Frame constraints
GridBagConstraints frameConstraints = new GridBagConstraints();
// Construct button
JButton addButton = new JButton("Add");
addButton.addActionListener(new ButtonListener());
// Add button to frame
frameConstraints.gridx = 0;
frameConstraints.gridy = 0;
frame.add(addButton, frameConstraints);
// Construct panel
panel.setPreferredSize(new Dimension(600, 600));
panel.setLayout(new GridBagLayout());
panel.setBorder(LineBorder.createBlackLineBorder());
// Add panel to frame
frameConstraints.gridx = 0;
frameConstraints.gridy = 1;
frameConstraints.weighty = 1;
frame.add(panel, frameConstraints);
// Pack frame
frame.pack();
// Make frame visible
frame.setVisible(true);
}
static class ButtonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent arg0)
{
// Clear panel
panel.removeAll();
// Create label and text field
JTextField jTextField = new JTextField();
jTextField.setSize(100, 200);
listOfTextFields.add(jTextField);
listOfLabels.add(new JLabel("Label " + indexer));
// Create constraints
GridBagConstraints textFieldConstraints = new GridBagConstraints();
GridBagConstraints labelConstraints = new GridBagConstraints();
// Add labels and text fields
for(int i = 0; i < indexer; i++)
{
// Text field constraints
textFieldConstraints.gridx = 1;
textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
textFieldConstraints.weightx = 0.5;
textFieldConstraints.insets = new Insets(10, 10, 10, 10);
textFieldConstraints.gridy = i;
// Label constraints
labelConstraints.gridx = 0;
labelConstraints.gridy = i;
labelConstraints.insets = new Insets(10, 10, 10, 10);
// Add them to panel
panel.add(listOfLabels.get(i), labelConstraints);
panel.add(listOfTextFields.get(i), textFieldConstraints);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
panel.add(new JLabel(), c);
// Increment indexer
indexer++;
panel.updateUI();
}
}
}
Here you go
// Construct panel
//panel.setPreferredSize(new Dimension(600, 600)); // No need for panel as it will get added to scrollpane
panel.setLayout(new GridBagLayout());
panel.setBorder(LineBorder.createBlackLineBorder());
JScrollPane scrollPane = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(600, 600));
// Add panel to frame
frameConstraints.gridx = 0;
frameConstraints.gridy = 1;
frameConstraints.weighty = 1;
frame.add(scrollPane, frameConstraints); // add acrollpane to frame
I have created a JScrollPane, added panel as its component and then added scrollPane to frame
Here
frame = new JFrame();
frame.setBounds(0, 0, 820, 950);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setLayout(null);
final JScrollPane scrollPanel = new JScrollPane(
panel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS
);
scrollPanel.setBounds(0, 0, 800, 900);
panel.setBounds(0, 0, 1920, 1080);
panel.setPreferredSize(new Dimension(1920, 1080));
frame.getContentPane().add(scrollPanel);
This code will work in general to add JScrollPane to JPanel. Adjust bounds of frame, panel and scrollpane according to your requirements but ensure that the bounds of JScrollPane are within the bounds of the frame otherwise the scrollpane will not be visible.
Add panel into JScrollPane, but create ScrollPane by this constractor
JScrollPane scrollPane = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
ScrollBars became visible only when panel size became bigger then parent component size.
On you jscrollpane you need to set vertical and horizontal bar schemes. for example
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class windows_test {
JFrame login = null;
JFrame inner_frame = null;
public windows_test() {
login = new JFrame();
login.setBounds(10, 10, 300, 300);
login.setLayout(new BorderLayout());
JPanel temp_panel = new JPanel();
temp_panel.add(new JTextArea("asd fsj adhf jsad kjfh sa dj kfh j sak ds fda f hsa kj d hf ks ad hf kjs ad h fk js ad h fjs da hf k j sahd kjfsh d jk fhs ad"));
login.setVisible(true);
JScrollPane scroll_pane = new JScrollPane(temp_panel);
scroll_pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); //SETTING SCHEME FOR HORIZONTAL BAR
scroll_pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
login.add(scroll_pane);
}
}
hope it will help you. if you are facing any problem then you can ask i will try to solve it.