GridBagLayout isn't paginated well before resizing - java

I'm new here.
I wrote a simple program in Java and for the GUI I'm using GridBagLayout.
The problem is that it doesn't paginate well until I touch the border of the window to resize the Frame. Here are some pictures of what I mean:
The main window before I resize the frame
The main window after I resize the frame
A part of my code:
public class TW2Tempi
{
public static void main(String[] args)
{
MainFrame mf = new MainFrame();
}
}
class MainFrame extends JFrame
{
GridBagConstraints gbc = new GridBagConstraints();
//other variables .....
public MainFrame()
{
super("Calcola i tempi dei tuoi attacchi");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
setPreferredSize(new Dimension(500, 300));
setMinimumSize(new Dimension(500, 300));
//setResizable(false); //I would also like to add this but then I wouldn't be able to "resize" and see everything (second picture)
//row 1 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//where gbc.gridy = 0
nobile = new JLabel("Orario di arrivo del nobile", SwingConstants.RIGHT);//right align
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.insets = new Insets(7,10,0,0);
gbc.fill = GridBagConstraints.BOTH;
add(nobile, gbc);
....
Do I have to initialize GridBagConstraints in a different way?

Related

Scrolled JLayer not behaving as a scrolled JPanel which it is supposed to replace

I'd like to decorate a JPanel with a JLayer, but am failing to understand why doing so messes up this panel being laid out inside a JScrollPane. The decorated component is supposed to act as a drop in replacement, but it does not appear to work in this case.
The following code creates two equivalent JPanels and puts them into another panel with CardLayout (so you may switch between them using the buttons). The only difference is that in one case the panel is decorated with a JLayer.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public class JLayerScroll extends JFrame {
public JLayerScroll() {
setTitle("Jumpy border");
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
createGui();
setSize(400, 200);
setLocationRelativeTo(null);
}
private void createGui() {
JPanel mainPanel = new JPanel(new CardLayout());
// two panels ("label panels"), first one decorated, second one not
mainPanel.add(createSingleScrolledComponent(new JLayer<JPanel>(createLabelPanel(), new LayerUI<JPanel>())), WITH_JLAYER);
mainPanel.add(createSingleScrolledComponent(createLabelPanel()), WITHOUT_JLAYER);
add(mainPanel);
createButtons(mainPanel);
}
private JPanel createSingleScrolledComponent(Component component) {
GridBagConstraints gbc;
JScrollPane scroll;
JPanel panel = new JPanel(new GridBagLayout());
scroll = new JScrollPane(component);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0d;
gbc.weighty = 1.0d;
panel.add(scroll, gbc);
return panel;
}
private JPanel createLabelPanel() {
GridBagConstraints gbc;
JPanel panel = new JPanel(new GridBagLayout());
JPanel entry = new JPanel(new GridBagLayout());
entry.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
JLabel label = new JLabel("Some input:");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
entry.add(label, gbc);
JTextField field = new JTextField(20);
field.setMinimumSize(new Dimension(field.getPreferredSize().width, field.getMinimumSize().height));
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
entry.add(field, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0d;
entry.add(Box.createHorizontalGlue(), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0d;
panel.add(entry, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1.0d;
panel.add(Box.createVerticalGlue(), gbc);
return panel;
}
private static final String WITH_JLAYER = "with-jlayer";
private static final String WITHOUT_JLAYER = "no-jlayer";
private void createButtons(final JPanel mainPanel) {
GridBagConstraints gbc;
JButton button;
JPanel actionsPanel = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0d;
actionsPanel.add(Box.createHorizontalGlue(), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
button = new JButton("With JLayer");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout layout = (CardLayout) mainPanel.getLayout();
layout.show(mainPanel, WITH_JLAYER);
}
});
actionsPanel.add(button, gbc);
gbc.gridx = 2;
gbc.gridy = 0;
button = new JButton("Without JLayer");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout layout = (CardLayout) mainPanel.getLayout();
layout.show(mainPanel, WITHOUT_JLAYER);
}
});
actionsPanel.add(button, gbc);
add(actionsPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JLayerScroll().setVisible(true);
}
});
}
}
If you pay attention to the red border in the two cases, you will notice that in one case it spans the whole available horizontal space (as expected), while in the other case, it only spans around visible components (label and text field).
Why is this happening and how do I achieve the same behavior as in the undecorated case (spanning through all available horizontal space)?
The only difference is that in one case the panel is decorated with a JLayer.
A difference between a JPanel and a JLayer is that the JLayer implements the Scrollable interface but a JPanel does not.
The getScrollableTracksViewportWidth() method controls whether the component added to the viewport should be displayed at its preferred size or the width of the viewport. The JLayer delegates to the JPanel, but since JPanel doesn't implement the Scrollable interface the JLayer implementation will return "false" which means the component should be displayed at its preferred width.
So a way to get around this is to use a wrapper panel for the JLayer:
//scroll = new JScrollPane(component);
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add( component );
scroll = new JScrollPane(wrapper);
Now the component added to the viewport of the scrollpane is a JPanel in both cases, so they should behave the same way.

GridBagLayout not getting expected result

Trying to understand how the GridBagLayout for Java works. Never used it before so its probably a stupid error that I've made.
My objective is to place a JLabel at the top center of the page. I've been using the java tutorials on Oracle but have had no luck. It seems the label remains in the center of the page. (center as in dead center of the x and y graph).
From what I understood, if I set the gridx and gridy constraint to 0, the compiler will look at the top, first row of the program and place the text their. I then used the PAGE START anchor to place the text in the center of the page. I'm not entirely sure what the weightx and weighty function does in my defence.
import javax.swing.*;
import java.awt.*;
class test
{
public static void main (String Args [])
{
//frame and jpanel stuff
JFrame processDetail = new JFrame("Enter information for processes");
JPanel panelDetail = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//label to add on top centre
JLabel label = new JLabel("LOOK AT ME");
//set size of frame and operation
processDetail.setSize(500,500);
processDetail.setDefaultCloseOperation(processDetail.EXIT_ON_CLOSE);
//add the label to panel
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 0; //not sure what this does entirely
c.gridx = 0; //first column
c.gridy = 0; //first row
panelDetail.add(label, c);
processDetail.add(panelDetail);
processDetail.setVisible(true);
}
}
You're only adding one thing to the GBL using container, and so it will be centered. If you add a 2nd component below your JLabel, the JLabel will show up at the top. For example,
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class Test2 {
private static void createAndShowGui() {
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.PAGE_START;
mainPanel.add(new JLabel("Look at me!", SwingConstants.CENTER), gbc);
gbc.gridy = 1;
gbc.gridheight = 10;
gbc.gridwidth = 10;
mainPanel.add(Box.createRigidArea(new Dimension(400, 400)), gbc);
JFrame frame = new JFrame("Test2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Myself, I'd use BorderLayout if I wanted my JLabel to be at the top.

GridBagLayout compnent's position not working

Hi i am beginner to java and doing small GUI using GridBagLayout. See the attached code and also the output . what i want is to place the JButtons on top left corner as per the position assigned in gridx and gridy . But it placing components in center instead of top left as expected , if i use Insets , gridx /gridy all that is working but not from proper coordinates so please see attached code and image and guide me about it
public rect()
{
JPanel panel = new JPanel( new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JButton nb1= new JButton("Button1 ");
JButton nb2= new JButton("Button2 ");
gbc.gridx=0;
gbc.gridy=0 ;
panel.add(nb1, gbc);
gbc.gridx=1;
gbc.gridy=1;
panel.add(nb2, gbc);
panel.setVisible(true);
JFrame frame = new JFrame("Address Book ");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300 );
frame.add(panel);
frame.setVisible(true);
}
OUTPUT : want these buttons on top left please guide me
I think the problem is more the use of setSize(..), you should rather use appropriate LayoutManager and call pack() on JFrame instance after adding all components to JFrame and before setting JFrame visible, also no need for panel.setVisible(..):
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JPanel panel = new JPanel(new GridBagLayout());
JButton nb1 = new JButton("Button1 ");
JButton nb2 = new JButton("Button2 ");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(nb1, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
panel.add(nb2, gbc);
JFrame frame = new JFrame("Address Book ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
}

Is it possible to make the elements inside a JPanel with GridBagLayout to start from the top left?

I have a Swing Form that contains a JScrollPane(activityScrollPane) for a JPanel(activityPanel). The panel contains a JTextField and a JButton (that is used to add more fields to the Panel). Now the problem is that the elements start from the center of the panel as in the image below (with the borders marking the activityScrollPane boundary)
Following is the code I am currently using to make the scroll pane and associated components.
//part of the code for creating the ScrollPane
final JPanel activityPanel = new JPanel(new GridBagLayout());
gbc.gridx=0;
gbc.gridy=0;
JScrollPane activityScrollPane = new JScrollPane(activityPanel);
//adding activity fields
activityFields = new ArrayList<JTextField>();
fieldIndex = 0;
activityFields.add(new JTextField(30));
final GridBagConstraints activityGBC = new GridBagConstraints();
activityGBC.gridx=0;
activityGBC.gridy=0;
activityGBC.anchor = GridBagConstraints.FIRST_LINE_START;
activityPanel.add(activityFields.get(fieldIndex),activityGBC);
fieldIndex++;
JButton btn_more = (new JButton("more"));
activityGBC.gridx=1;
activityPanel.add(btn_more,activityGBC);
How can I make the JTextField and the JButton or for that matter any component to appear on the top left corner of the JScrollPane. I have already tried using
activityConstraints.anchor = GridBagConstraints.NORTHWEST;
as pointed in the SO post, but it does not at all seem to work.
You simply forgot to provide any weightx/weighty values, atleast one having a non-zero value will do. have a look at this code example :
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo
{
private JTextField tfield1;
private JButton button1;
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
tfield1 = new JTextField(10);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield1, gbc);
button1 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button1, gbc);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GridBagLayoutDemo().displayGUI();
}
});
}
}
Latest EDIT : No spacing along Y-Axis
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo
{
private JTextField tfield1;
private JButton button1;
private JTextField tfield2;
private JButton button2;
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
tfield1 = new JTextField(10);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 1.0;
//gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield1, gbc);
button1 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button1, gbc);
tfield2 = new JTextField(10);
gbc.weightx = 1.0;
gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield2, gbc);
button2 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button2, gbc);
JScrollPane scroller = new JScrollPane(contentPane);
frame.add(scroller);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GridBagLayoutDemo().displayGUI();
}
});
}
}
Sorry as my answer me be on the off-side of what you have asked, but why dont you use GroupLayout instead of GridBag Layout, thats much more easier to handle
try it with BorderLayout: controls.setLayout(new BorderLayout()); and then apply it for your JPanel controls.add(yourPanel, BorderLayout.PAGE_START);
I also have problems with GridBagLayout so i solved it with BorderLayout and it works so fine.
So i wrote for your little example:
private void initComponents() {
controls = new Container();
controls = getContentPane();
controls.setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
field = new JTextField(20);
c.gridx = 0;
c.gridy = 0;
panel.add(field, c);
one = new JButton("Go!");
c.gridx = 1;
c.gridy = 0;
panel.add(one, c);
controls.add(panel, BorderLayout.PAGE_START);
}
Hope it helps!
I think this could be simple and possible, you can
put Nested JPanel to the JScrollPane
to this JPanel
put JPanels contains JComponent to the GridLayout (notice about scrolling, you have to change scrolling increment)
or use most complex JComponents as
put JPanels contains JComponent as Item to the JList
put JPanels contains JComponent as row to the JTable (with only one Column, with or without TableHeader)
Add one panel at the right and one at the bottom.
Right Panel:
Set Weight X to 1.0.
Set Fill to horizontal.
Bottom Panel:
Set Weight Y to 1.0.
Set Fill to vertical
There may be better ways to that, but this one worked for me.

Java 2 JPanel's in one JFrame layout

Hi I am trying to add 2 JPanel's to a JFrame that take the full width and height of the JFrame.I managed to add them with GridBagLayout() but I can't seem to set the size of the JPanels using the setsize().I have also tryied to used ipady and ipadx while that seemed to work at first after I aded some buttons the whole layout became a mess.Here is my code:
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setVisible(true);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
tradeframe.setLayout(new GridBagLayout());
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
GridBagConstraints a = new GridBagConstraints();
a.gridx = 0;
a.gridy = 0;
a.weightx = 360;
a.weighty = 300;
//a.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P1panel , a);
GridBagConstraints b = new GridBagConstraints();
b.gridx = 1;
b.gridy = 0;
b.weightx = 360;
b.weighty = 300;
// b.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P2panel , b);
How can I make that each JPanel is 300px width and 400px in height?
for GridBaglayout you have to set
fill
anchor
weightx and weighty
gridx / gridy (depend of orientations)
then is possible for example
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderPanels extends JFrame {
private static final long serialVersionUID = 1L;
public BorderPanels() {
setLayout(new GridBagLayout());// set LayoutManager
GridBagConstraints gbc = new GridBagConstraints();
JPanel panel1 = new JPanel();
Border eBorder = BorderFactory.createEtchedBorder();
panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridx = gbc.gridy = 0;
gbc.gridwidth = gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = gbc.weighty = 20;
add(panel1, gbc); // add compoenet to the COntentPane
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "60pct"));
gbc.gridy = 1;
gbc.weightx = gbc.weighty = 60;
//gbc.insets = new Insets(2, 2, 2, 2);
add(panel2, gbc); // add component to the COntentPane
JPanel panel3 = new JPanel();
panel3.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridy = 2;
gbc.weightx = gbc.weighty = 20;
gbc.insets = new Insets(2, 2, 2, 2);
add(panel3, gbc);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // important
pack();
setVisible(true); // important
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() { // important
public void run() {
BorderPanels borderPanels = new BorderPanels();
}
});
}
}
on most cases will be better use another LayoutManager
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
Box content = new Box(BoxLayout.X_AXIS);
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
content.add(P1panel);
content.add(P2panel);
tradeframe.setContentPane(content);
tradeframe.setVisible(true);
Invoke setPreferredSize(new Dimension(int width, int height)); method on your panel objects.
Here is the way to do that :
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutTest
{
public GridBagLayoutTest()
{
JFrame frame = new JFrame("GridBag Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
JPanel leftPanel = new JPanel();
leftPanel.setBackground(Color.WHITE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
container.add(leftPanel, gbc);
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.BLUE);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.fill = GridBagConstraints.BOTH;
container.add(rightPanel, gbc);
frame.setSize(600, 400);
frame.setVisible(true);
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new GridBagLayoutTest();
}
};
SwingUtilities.invokeLater(runnable);
}
}
OUTPUT :
You are using setSize() instead of setPreferredSize(). The difference is somewhat misleading and I would consider it a gotcha in java. Some more information about what the difference between the two can be found here.
The article I link has some other pitfalls/gotchas and a useful read if you are new to Java.

Categories