Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problems with JSeparator together with GridBagLayout

 
Emil Karlsson
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Does anyone know why a JSeparator shows perfectly in GridLayout, but when I change to GridBagLayout it does not appear in the frame?
Thanks in advance, Emil
//Works perfect
import java.awt.*;
import javax.swing.*;
public class SeparatorTest {
public static void main(String[] args) {
new SeparatorTest();
}
public SeparatorTest(){
JFrame frame = new JFrame();
frame.setSize(200,200);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,1));
JLabel label = new JLabel("label 1");
panel.add(label);
JSeparator sep = new JSeparator(JSeparator.HORIZONTAL);
Color col = new Color(125,125,125);
sep.setForeground(col);
panel.add(sep);
label = new JLabel("label 2");
panel.add(label);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
//This does not show the separator
import java.awt.*;
import javax.swing.*;
public class SeparatorTestWithGridBag {
public static void main(String[] args) {
new SeparatorTestWithGridBag();
}
public SeparatorTestWithGridBag(){
GridBagLayout grid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
JFrame frame = new JFrame();
frame.setSize(200,200);
JPanel panel = new JPanel();
panel.setLayout(grid);
JLabel label = new JLabel("label 1");
gbc.gridy=0;
gbc.gridx=0;
gbc.weightx=10.0;
gbc.weighty=10.0;
grid.setConstraints(label,gbc);
panel.add(label);
JSeparator sep = new JSeparator(JSeparator.HORIZONTAL);
Color col = new Color(125,125,125);
sep.setForeground(col);
gbc.gridy=1;
gbc.gridx=0;
grid.setConstraints(sep,gbc);
panel.add(sep);
label = new JLabel("label 2");
gbc.gridy=2;
gbc.gridx=0;
grid.setConstraints(label,gbc);
panel.add(label);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the constraints of the JSeparator, add the line :


To remove the horizontal fill for the second label, you would need to set the fill to :
 
Emil Karlsson
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Nate!
"Sometimes it's hard to see the forest, because of all the trees"

Emil
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic