The gridBagLayout and the JscrollPanel

Hi:
1)GridBagLayout
When I tried to use the GridBagLayout, I found that I can not change the weight of each component added in the container.
For example,In the contentPanel of the JDialog, I added two sub panels:leftPanel and rightPanel.However the leftPanel and the rightPanel take the same width of the main dialog,I just want the leftPanel take 60% of the width of the JDialog. I have tried to definte the weightx parameter of leftPanel's GridBagContrains,but it seems not work.
Also I found that if I add a empty Jpanel in a GridBagLayout managed JFrame,it take a small space ,after I add some compontens in the Jpanel, it is resized,
In fact I want to control the compontent just as the size I wanted using the releative position.That's to say, even the Jpanel is empty,it should take up its own size I setted.
So is there any ideas?
2)The JScrollPanel.
The leftPanel mentioned above is a JScrollPanel,and I want to show some little vector symbols in this panel,the symbols should changed when a JCombox( has been added to the main frame) changed.
So I set the view port of the JScrollPanel to a new Jpanel(symbolListPanel:used to display the symbols, and each symbol will be draw in a SymbolPanel which extends the Jpanel and override the paint() method). I set this symbolListPanel use the GridBagLayout. I want there are three symbols displayed in each row, so I use the following codes:
GridBagConstraints c=new GridBagConstraints();
c.fill=both;c.weightx=c.weighty=1;
Symbols[] s=getVectorSymbols();
for(int i=0;i<s.length();i++) {
  c.gridx=i%3;
  c.gridy=i/3;
  symbolListPanel.add(new SymbolPanel(s),c); //
symbolListPanel.repaint();-----------------------
Well, when I run the application, the symbols are displayed,when I add 6 symbols, the symbolListPanel is divided to a 2(rows)x3(columns) grid,it looks well,however when I add 9 symbols, the symbolListPanel is divided to a 3(rows)x3(columns) grid,this is no problem,but the ScrollBar is never displayed,also each SymbolPanel is resized smaller to fit the size of the visible space of the leftPanel(JScrollPanel). In fact what I really need is the size SymbolPanel is never changed, when the visible  of the leftPanel is not large enough to show all the symbols, the scrollBar should display.
BTW, in the SymbolPanel I have used the following method tried to controll the size :setPreferredSize(////);
setMaximumSize(getPreferredSize);
setMinimumSize(getPreferredSize) ;I think use the above three method can absolutely control the size of the Symbolpanel (then it can not be resized).
But it seems not. why?
3) When I change the combox, the symbols should chang. however the changed symbols can never be  visible  unless I resize the dialog.
I thought if it is the repaint problem of the dialog. But I have call the  symbolListPanel.repaint() method,it seems that the repaint method of the sub compontent of the symbolListpanel is not called. At last I have to use the following method to make the changed symbols visible:dialog.setVisible(false);
dialog.setVisible(true); // Set the main dialog unvisible,then set it visible, so all the compontents will be repainted,and it works.
// However I know this is a stupid method, is there any normal ways ?
Edited by: apachemaven on 2010-7-25 ??2:08                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Thanks, I apology for my unpolite.
The problem is encountered in company, and our working computer is not allowed to communicate with extra hardware such as the portable hardisk.
So it is not easy to make a simple example... It realated too many other objects which I can not simulate.
In fact I use the Absolute Positioning to solve the problem(Though it is not a good idea).
In this form I found another discussion about the GirdBagLayout at [thread.jspa?threadID=5446065&tstart=0|http://forums.sun.com/thread.jspa?threadID=5446065&tstart=0] ,and Sarcommand said:
A GridBagLayout will try to give every component space according to its preferred size.If so, does it mean I should set the prefered size of each component?
Here I write a simple test:
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import java.awt.Frame;
import java.awt.BorderLayout;
import javax.swing.JDialog;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import java.awt.Insets;
public class GridTest extends JDialog {
     private static final long serialVersionUID = 1L;
     private JPanel jContentPane = null;
     private JPanel leftPanel = null;
     private JPanel rightPanel = null;
     private JButton okButton = null;
     private JButton cancelButton = null;
     public GridTest(Frame owner) {
          super(owner);
          initialize();
     private void initialize() {
          this.setSize(495, 515);
          this.setContentPane(getJContentPane());
          this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
     private JPanel getJContentPane() {
          if (jContentPane == null) {
               GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
               gridBagConstraints1.gridx = 1;
               gridBagConstraints1.weightx = 0.3;
               gridBagConstraints1.weighty = 1.0;
               gridBagConstraints1.gridy = 0;
               GridBagConstraints gridBagConstraints = new GridBagConstraints();
               gridBagConstraints.gridx = 0;
               gridBagConstraints.fill = GridBagConstraints.BOTH;
               gridBagConstraints.weightx = 0.7;
               gridBagConstraints.weighty = 1.0;
               gridBagConstraints.gridy = 0;
               jContentPane = new JPanel();
               jContentPane.setLayout(new GridBagLayout());
               jContentPane.add(getLeftPanel(), gridBagConstraints);
               jContentPane.add(getRightPanel(), gridBagConstraints1);
          return jContentPane;
     private JPanel getLeftPanel() {
          if (leftPanel == null) {
               leftPanel = new JPanel();
               leftPanel.setLayout(new GridBagLayout());
               leftPanel.setBorder(BorderFactory.createTitledBorder("Left"));
          return leftPanel;
     private JPanel getRightPanel() {
          if (rightPanel == null) {
               GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
               gridBagConstraints2.gridx = 1;
               gridBagConstraints2.fill = GridBagConstraints.BOTH;
               gridBagConstraints2.insets = new Insets(0, 10, 0, 0);
               gridBagConstraints2.gridy = 0;
               rightPanel = new JPanel();
               rightPanel.setLayout(new GridBagLayout());
               rightPanel.add(getOkButton(), new GridBagConstraints());
               rightPanel.add(getCancelButton(), gridBagConstraints2);
          return rightPanel;
     private JButton getOkButton() {
          if (okButton == null) {
               okButton = new JButton();
               okButton.setText("OK");
          return okButton;
     private JButton getCancelButton() {
          if (cancelButton == null) {
               cancelButton = new JButton();
               cancelButton.setText("Cancel");
          return cancelButton;
     public static void main(String[] args) {
          new GridTest(null).setVisible(true);
}In this test, I want the left panel take the 70% of the widht of the whole dialog,when the dialog first set up, I found the leftpanel take only about 50%, when I resize(increase) the dialog, it seems that the leftpanel's percentge increase.
However this is not what I want, I set the size of the whole dialog to (495,515),and I want the left take about 70%X495 always.
So, is there any way using the GridbagLayout?

Similar Messages

  • GridBagLayout and Panel Border problem

    I have 3 panels like
    A
    B
    C
    and the C panel has a Mouse Listener that on a mouseEntered creates a border around the same panel and on a mouseExited clears that border.
    When this border is created the A and B panels go up a little bit .. they move alone when the border is created.
    Is there any way to fix this problem? Is there any way to get the panels static?
    the code is close to the following:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.border.TitledBorder;
    import java.awt.event.*;
    import java.text.NumberFormat;
    public class Game extends JFrame implements MouseListener
    JPanel game, options, top, down, middle;
    NumberFormat nf;
    public Game() {
    super("Game");
    nf = NumberFormat.getPercentInstance();
    nf.setMaximumFractionDigits(1);
    JPanel center = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = gbc.BOTH;
    gbc.weighty = 1.0;
    gbc.weightx = 0.8;
    center.add(getGamePanel(), gbc);
    gbc.weightx = 0.104;
    center.add(getOptionsPanel(), gbc);
    Container cp = getContentPane();
    // use the JFrame default BorderLayout
    cp.add(center); // default center section
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setSize(700,600);
    // this.setResizable(false);
    setLocationRelativeTo(null);
    setVisible(true);
    addComponentListener(new ComponentAdapter()
    public void componentResized(ComponentEvent e)
    showSizeInfo();
    showSizeInfo();
    private void showSizeInfo()
    Dimension d = getContentPane().getSize();
    double totalWidth = game.getWidth() + options.getWidth();
    double gamePercent = game.getWidth() / totalWidth;
    double optionsPercent = options.getWidth() / totalWidth;
    double totalHeight = top.getHeight() + middle.getHeight() + down.getHeight();
    double topPercent = top.getHeight() / totalHeight;
    double middlePercent = middle.getHeight() / totalHeight;
    double downPercent = down.getHeight() / totalHeight;
    System.out.println("content size = " + d.width + ", " + d.height + "\n" +
    "game width = " + nf.format(gamePercent) + "\n" +
    "options width = " + nf.format(optionsPercent) + "\n" +
    "top height = " + nf.format(topPercent) + "\n" +
    "middle height = " + nf.format(middlePercent) + "\n" +
    "down height = " + nf.format(downPercent) + "\n");
    private JPanel getGamePanel()
    // init components
    top = new JPanel(new BorderLayout());
    top.setBackground(Color.red);
    top.add(new JLabel("top panel", JLabel.CENTER));
    middle = new JPanel(new BorderLayout());
    middle.setBackground(Color.green.darker());
    middle.add(new JLabel("middle panel", JLabel.CENTER));
    down = new JPanel(new BorderLayout());
    down.setBackground(Color.blue);
    down.add(new JLabel("down panel", JLabel.CENTER));
    // layout game panel
    game = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1.0;
    gbc.fill = gbc.BOTH;
    gbc.gridwidth = gbc.REMAINDER;
    gbc.weighty = 0.2;
    game.add(top, gbc);
    gbc.weighty = 0.425;
    game.add(middle, gbc);
    gbc.weighty = 0.2;
    game.add(down, gbc);
    down.addMouseListener(this);
    return game;
    private JPanel getOptionsPanel()
    options = new JPanel(new BorderLayout());
    options.setBackground(Color.pink);
    options.add(new JLabel("options panel", JLabel.CENTER));
    return options;
    // mouse listener events
         public void mouseClicked( MouseEvent e ) {
    System.out.println("pressed");
         public void mousePressed( MouseEvent e ) {
         public void mouseReleased( MouseEvent e ) {
         public void mouseEntered( MouseEvent e ) {
    Border redline = BorderFactory.createLineBorder(Color.red);
    JPanel x = (JPanel) e.getSource();
    x.setBorder(redline);
         public void mouseExited( MouseEvent e ){
    JPanel x = (JPanel) e.getSource();
    x.setBorder(null);
    public static void main(String[] args ) {
    Game exe = new Game();
    exe.show();
    }

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    public class Game extends JFrame implements MouseListener{
      JPanel game, options, top, down, middle;
      NumberFormat nf;
      public Game() {
        super("Game");
        nf = NumberFormat.getPercentInstance();
        nf.setMaximumFractionDigits(1);
        JPanel center = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = gbc.BOTH;
        gbc.weighty = 1.0;
        gbc.weightx = 0.8;
        center.add(getGamePanel(), gbc);
        gbc.weightx = 0.104;
        center.add(getOptionsPanel(), gbc);
        Container cp = getContentPane();
        // use the JFrame default BorderLayout
        cp.add(center); // default center section
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(700,600);
        // this.setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true);
        addComponentListener(new ComponentAdapter(){
            public void componentResized(ComponentEvent e){
            showSizeInfo();
        showSizeInfo();
      private void showSizeInfo(){
        Dimension d = getContentPane().getSize();
        double totalWidth = game.getWidth() + options.getWidth();
        double gamePercent = game.getWidth() / totalWidth;
        double optionsPercent = options.getWidth() / totalWidth;
        double totalHeight = top.getHeight() + middle.getHeight() + down.getHeight();
        double topPercent = top.getHeight() / totalHeight;
        double middlePercent = middle.getHeight() / totalHeight;
        double downPercent = down.getHeight() / totalHeight;
        System.out.println("content size = " + d.width + ", " + d.height + "\n" +
            "game width = " + nf.format(gamePercent) + "\n" +
            "options width = " + nf.format(optionsPercent) + "\n" +
            "top height = " + nf.format(topPercent) + "\n" +
            "middle height = " + nf.format(middlePercent) + "\n" +
            "down height = " + nf.format(downPercent) + "\n");
      private JPanel getGamePanel(){
        // init components
        top = new JPanel(new BorderLayout());
        top.setBackground(Color.red);
        top.add(new JLabel("top panel", JLabel.CENTER));
        middle = new JPanel(new BorderLayout());
        middle.setBackground(Color.green.darker());
        middle.add(new JLabel("middle panel", JLabel.CENTER));
        down = new JPanel(new BorderLayout());
        down.setBackground(Color.blue);
        down.add(new JLabel("down panel", JLabel.CENTER));
        // layout game panel
        game = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.weightx = 1.0;
        gbc.fill = gbc.BOTH;
        gbc.gridwidth = gbc.REMAINDER;
        gbc.weighty = 0.2;
        game.add(top, gbc);
        gbc.weighty = 0.425;
        game.add(middle, gbc);
        gbc.weighty = 0.2;
        game.add(down, gbc);
        down.addMouseListener(this);
        return game;
      private JPanel getOptionsPanel(){
        options = new JPanel(new BorderLayout());
        options.setBackground(Color.pink);
        options.add(new JLabel("options panel", JLabel.CENTER));
        return options;
      public void mouseClicked( MouseEvent e ) {
        System.out.println("pressed");
      public void mousePressed( MouseEvent e ) {
      public void mouseReleased( MouseEvent e ) {
      public void mouseEntered( MouseEvent e ) {
        Border redline = new CalmLineBorder(Color.red);
        JPanel x = (JPanel) e.getSource();
        x.setBorder(redline);
      public void mouseExited( MouseEvent e ){
        JPanel x = (JPanel) e.getSource();
        x.setBorder(null);
      public static void main(String[] args ) {
        Game exe = new Game();
        exe.setVisible(true);
    class CalmLineBorder extends LineBorder{
      public CalmLineBorder(Color c){
        super(c);
      public CalmLineBorder(Color c, int thick){
        super(c, thick);
      public CalmLineBorder(Color c, int thick, boolean round){
        super(c, thick, round);
      public Insets getBorderInsets(Component comp){
        return new Insets(0, 0, 0, 0);
    }

  • TableLayout... better than GridBagLayout and easier to boot.

    Just in case any of you haven't seen this, if you go to java.sun.com and do a search on TableLayout, you'll find a very powerful easy to use and dynamic layout that I feel is far better than any other layout for most tasks. It automatically resizes components to the cell sizes, you can position them within cells, expand them across cells, and dynamically add/remove and hide/show cells (for both columns and rows) at any time. This last one I think is great because it avoids things like having to create two JPanels, one for a short form, and one for a much more involved form. I suppose there might be other ways, but with TableLayout, you simply supply the long form, hide the rows/cells you don't need for the short form, then show them again if the long form is desired. It is simple to use too. Much like a spread sheet or JTable, you just position a component into a container with a TableLayout into an appropriate defined cell in x,y fashion.
    Give it a try. Post some feedback here.

    Sure, its easy to use.
    One question,
    I have a couple of components that I have in a panel. I have used the option FILL, to make all components the same size. This result in that the last component get a bigger space then the others. If I make the window smaller it first resizes the last component til it is the same size as all the others. If I make my panel even smaller, the last component gets a bigger space then the others again.
    Is there a way to always have the same size of the components ?

  • Displaying the content of one JPanel in an other as a scaled image

    Hi,
    I'd like to display the content of one JPanel scaled in a second JPanel.
    The first JPanel holds a graph that could be edited in this JPanel. But unfortunately the graph is usually to big to have a full overview over the whole graph and is embeded in a JScrollPanel. So the second JPanel should be some kind of an overview window that shows the whole graph scaled to fit to this window and some kind of outline around the current section displayed by the JScrollPanel. How could I do this?
    Many thanks in advance.
    Best,
    Marc.

    Hi,
    I'd like to display the content of one JPanel scaled
    in a second JPanel.
    The first JPanel holds a graph that could be edited
    in this JPanel. But unfortunately the graph is
    usually to big to have a full overview over the whole
    graph and is embeded in a JScrollPanel. So the second
    JPanel should be some kind of an overview window that
    shows the whole graph scaled to fit to this window
    and some kind of outline around the current section
    displayed by the JScrollPanel. How could I do this?
    Many thanks in advance.
    Best,
    Marc.if panel1 is the graph and panel2 is the overview, override the paintComponent method in panel2 with this
    public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.scale(...,...);
    panel1.paint(g2);
    }

  • Need Help to update the labels in the GUI syncronously - Swing application

    Hello everyone,
    I need some help regarding a swing application. I am not able to syncronously update the counters and labels that display on my Swing GUI as the application runs in the background. But when the running of application is completed, then the labels on the GUI are getting updated, But I want update the labels and counters on the GUI syncronously as the code executes... below I am giving the format of the code I have written..............
    public class SwingApp extends JFrame{
            // here i have declared the label and component varibles like...
                      private JTextField startTextField;
           private JComboBox maxComboBox;
           private JTextField logTextField;
           private JTextField searchTextField;
           private JLabel imagesDownloaded1;
           private JLabel imagesDownloaded2;
           private JLabel imagesDidnotDownload1;
           private JLabel imagesDidnotDownload2;
                      private JButton startButton;
    //now in the constructer.............
    public Swing(){
    //I used gridbaglayout and wrote the code for the GUI to appear....
    startButton = new JButton("Start Downloading");
        startButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            try{
                 actionSearch();   //actionSearch will contain all the code and the function calls of my application...........
            }catch(Exception e1){
                 System.out.println(e1);
        constraints = new GridBagConstraints();
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 5, 5);
        layout.setConstraints(startButton, constraints);
        searchPanel.add(startButton);
    //update is a function which initiates a thread which updates the GUI. this function will be called to pass the required variables in the application
    public void update(final int count_hits, final int counter_image_download1, final int didnot_download1) throws Exception{
         Thread thread = new Thread(new Runnable() {
             public void run() {
                  System.out.println("entered into thread");
                  System.out.println("the variable that has to be set is " + count_hits);
                  server_hits_count.repaint(count_hits);
                  server_hits_count.setText( " "+ Integer.toString(count_hits));
                  imagesDownloaded2.setText(" " + Integer.toString(counter_image_download1));
                  imagesDidnotDownload2.setText(" " + Integer.toString(didnot_download1));
                  repaint();
         //this.update(count_hits);
         thread.start();
    //Now in main............................
    public static void main(String[] args){
    Swing s = new Swing();
    s.setVisible(true);
    }//end of main
    }//end of class SwingAbove I have given the skeleton code of my application........ Please tell me how to update the GUI syncronously...
    Please its a bit urgent...............
    Thank you very much in advance
    chaitanya

    First off, note that this question should have been posted in the Swing section.
    GUI events run in a separate thread (the AWT / Event Dispatch Thread) than your program.
    You should be invoking AWT/Swing events via SwingUtilities.invokeLater().
    If for whatever reason you want to have the program thread wait for the event to process
    you can use invokeAndWait().
    http://java.sun.com/javase/6/docs/api/javax/swing/SwingUtilities.html

  • How do I get the GidBagLayout location from my buttons?

    How could I get the location of my JButtons (or JLabels) in my GridBoxLayout?
    I've tried all that I could think of..
    here some code sample
    JButton button;
        GridBagLayout layout = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
            c.weightx = 0.5;
            c.weighty = 0.5;
            c.insets = new Insets(20,20,20,20);
            button = new JButton("Button 1");
            c.gridx = 0;
            c.gridy = 0;
              button.addActionListener(this);
            centerPanel.add(button, c);
            button = new JButton("Button 2");
            c.gridx = 1;
            c.gridy = 0;
              button.addActionListener(this);
            centerPanel.add(button, c);
              System.out.println(((JButton)e.getSource()).getText());
              System.out.println(layout.getLayoutOrigin());
              //System.out.println(((JButton)e.getSource()).);
              //System.out.println(((JButton)e.getSource()).location());
              System.out.println(e.getSource().toString());
              System.out.println(layout.getLayoutDimensions());
    //          System.out.println(layout.lookupConstraints(((JButton)e.getSource())));
              System.out.println(layout.getLayoutOrigin());I think that's all you experts would need..
    what I'm trying to do is when I click on one of them buttons then fetch where that buttons is (in the GridBagLayout, not absolute) and be able to add a new button to the side or under the clicked button..
    the System.out.println(layout.getLayoutOrigin()); does seem to give me x=0 and y=0 but that's the same with all buttons so it isn't good enough

    I think that's all you experts would need..You would think wrong. We need a SSCCE to see exactly
    what you are doing.
    see http://homepage1.nifty.com/algafield/sscce.html,
    In general component don't have a size or location
    until the GUI is visible. That is the layout manager
    isn't invoked until the component is displayed.
    If you want to add a component after the component
    you click on then you would probably need to use the
    add(...) method that takes a position variable as a
    parameter.yes I think I need to use the add(..) and a position variable
    the problem is that I need to get the position variable from the other component so I could put the new component at the right position
    as for the SSCCE I do think that I do that..
    but for some extra information
    I'm writing an applet.. and I use a borderlayout for some component.. in the center panel I've placed a GridBagLayout and some buttons.. I've given the buttons an ActionListener and now I want to get the location in the GridBag of the Button I've pressed
    so when I click one of them buttons I want to know it's location.. as in X=1, Y=2 or something
    so I could place the new button on X=1, Y=3

  • How to set contents begin at the first line?

    I created a JPanel setting CENTER, then use GridBagLayout and want contents begin at the top, not in the center. I try using anchor, but it doesn't work. Please help me sort it out. Thanks.
    Here my code:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class gridBagLayoutTest extends JFrame{
        public gridBagLayoutTest() {
          super("test");
          Container con = this.getContentPane();
          JPanel jp=new JPanel();
          GridBagLayout gb=new GridBagLayout();
          GridBagConstraints c=new GridBagConstraints();
          c.fill=GridBagConstraints.BOTH;
          jp.setLayout(gb);
          c.gridx=0;
          c.gridy=0;
          JButton jb=new JButton("Button1");
          gb.setConstraints(jb,c);
          jp.add(jb);
          con.add(jp, BorderLayout.CENTER);
          setSize(250,250);
          setVisible(true);
          addWindowListener(
               new WindowAdapter(){
                   public void windowClosing(WindowEvent e){
                      System.exit(0);
    public static void main(String[] args){
          new gridBagLayoutTest();

    Hi,
    well your question seems not clear, but anyway..i would suggest u make use of the NORTHWEST, NORTH, NORTHEAST, EAST constraints of the GridBagLayout..its the most tedious and difficult layout manager in java
    i.e
    GridBagLayout gl;
    GridBagConstraints gbc;
    gl = new GridBagLayout();
    gbc = new GridBagConstraints();
    yourpanel.setLayout (gl);
    gbc.anchor=GridBagConstraints.NORTHWES;
    gbc.gridx=1;     //an example of where u want to position the component at northwest.
    gbc.gridy = 4;
    gl.setConstraints (yourcomponent,gbc);
    yourpanel.add (yourcomponent);But note that by default in java..no matter the type of layout manager used...adding of components to containers starts at at the middle..and get pushed up...depending of the number of components u add up.
    Another option for u is to set layout = NULL...then u will have to work with Dimesion..to position your components.
    i.e
    Jlabel label1 = new JLabel("ddd");
    panel.setLayout (null);
    jLabel.setBounds(new Rectangle(9, 207, 120, 26));
    panel.add(jlabel1);I hope this helps.
    Regards.
    Olumide

  • What is the easiest way to assemble forms in Swing ?

    Dear friends,
    I�m doing a nice job with GridBagLayout, and my forms are well designed as well.....
    but now I have to share my tasks with some other guys without swing experience... and I�m afraid to teach GridBagLayout will cause more problems than productivity....
    I have decided to use some framework or another layout manager,....
    can you tell me what is the easiest way to construct forms in Swing ??
    best regards,
    Felipe Ga�cho

    First off, make them learn GridBagLayout as well as the other layout managers (like BorderLayout). Have them play around with JBuilder's visual editor, making note of what changes visually do to the underlying code, etc. It will serve them well.
    I have yet to find an "easier" layout manager that doesn't at some point tie your hands and end up making life more difficult. With GridBagLayout, BorderLayout and use of subcontainers, you can do anything you might need. :-)
    I wouldn't say absolute positioning is anti-Java.
    It's certainly more work to deal with in most cases.
    . You can always get the screen resolution and
    adjust your sizes accordingly. It's still 100% pure
    Java code. It is anti in that it doesn't follow the general spirit of Java. Yes it will be 100% Java code, but it will be at least 90% crap as well. :-) You then can't easily do localization, changes in the look & feel mess up your app, your components won't resize properly, any change to a label's text causes you to have to tweak everything, etc. Ghastly stuff. It is the lazy way to get the GUI to look like someones mock up, but that is all it's good for.
    If you run across a GUI done with absolute positioning, you have my permission to give the responsible developer an atomic wedgie.

  • Maximum size of a JComboBox in a GridBagLayout

    I'm having a problem with a JComboBox inside a GridBagLayout. The general layout is a GridBag with labels / combo / textfields on the first line, a large table in a scrollpane that takes all columns on the second line, and a few labels / combo / textfields on the third.
    As long as the combo on the first combo is empty, it looks fine. When it gets populated, the combo gets resized to the size of the largest text. I would like to have it smaller and truncate the text.
    I tried to set maximum size, but the GridBag doesnt care. I've been trying with weightx but no success.
    What should I do ?

    And I would be interested which LayoutManager you prefer using.I don't use a single Layout Manager. I use a combination of Layout Managers to do the job. Thats why this question doesn't have a specific example. Remember LayoutManagers can be nested. The default layout manager for a frame is a border layout. That great for the general look of your application.
    a) you add a toolbar to the north
    b) you add a status bar to the south
    c) you add your main panel to the center.
    the main panel in turrn may use nested panels depending on your requirements. I don't do a lot of screen design but I typically use BorderLayout, FlowLayout, GridLayout and BoxLayout. GridBagLayout and SpringLayout have too many constraints to learn and master. They may be good for a GUI tool that only uses a single layout manager for the entire GUI, but I believe a better design is to break down the form into smaller more manageable areas and group components and use the appropriate layout manager for the group. That may or may not be a GridBagLayout for the small group, but I don't think you should force the entire form to use a GridbagLayout.

  • Exact column (row) size with GridBagLayout??

    Hello there,
    I have a question regarding GridBagLayout and EXACT (relative) dimensions
    of columns and rows. Have you ever had (and solved) this problem? Thank you
    for help!!
    My situations: let's say I'd like to have two buttons, the first should fill
    up 1/4 of the horizontal space and the second should fill up the remaining
    3/4 of the space. But I'd like them to fill up the space EXACTLY (if there
    is enough space of course, I'm not speaking about horizontal space 10
    pixels...). I tried to achieve this by the following code:
    GridBagLayout grid = new GridBagLayout();
    getContentPane().setLayout(grid);
    GridBagConstraints c = new GridBagConstraints();
    // button1
    JButton b1 = new JButton("A");
    c.gridx = 0; c.gridy = 0;
    c.gridwidth = 1; c.gridheight = 1;
    c.weightx = 1.0; c.weighty = 1.0; // <--- weigthx is 1.0 the other
    button will have 3.0
    c.fill = GridBagConstraints.BOTH;
    c.ipadx = 0; c.ipady = 0;
    c.insets = new Insets(0,0,0,0);
    grid.setConstraints(b1, c);
    getContentPane().add(b1);
    // button2
    JButton b2 = new JButton("B");
    c.gridx = 1; c.gridy = 0;
    c.gridwidth = 1; c.gridheight = 1;
    c.weightx = 3.0; c.weighty = 1.0; // <--- weigthx is 3.0 the first has
    1.0
    c.fill = GridBagConstraints.BOTH;
    c.ipadx = 0; c.ipady = 0;
    c.insets = new Insets(0,0,0,0);
    grid.setConstraints(b2, c);
    getContentPane().add(b2);
    This really lays out the buttons in fashiion 1:3 but not exactly, there
    always about 10-15 pixels that are extra...
    I tried to have the weigthx in range <0, 1> so, the button b1 has weigthx =
    0.25 and the second one has weigth = 0.75. But it does not work either...
    Can you help me please?
    David
    ps. Why do I need this exact layout? Because I have 3 tabs (JTabbedPane) and
    all of them display components with this 1:3 layout. But when I click on
    different tabs I can see that the boundary betweeen the two components
    "jumps" slightly from tab to tab which drives me crazy because things like
    this should not be part of program that wants to look "professionally-done".

    Ok, but I don't know the dimensions... I wanted the Layout manager to do the job. I was wondering, maybe I didn't set something else. But thank you!!
    ps. how come that the layout manager displays the layout almost perfectly? the ratio is almost 1:3 but not exactly.

  • GridBagLayout with JScrollPane difficulties

    I'm having problems getting the components in a JPanel to layout properly. I'm using GridBagLayout and I'm having problems with adding a JScollPane.
    The JScrollPane in the layout (holding a subclass of a JPanel as its viewport) does not work properly in some case. When the viewport won't display fully, and requires scroll bars, the JScrollPane shrinks to a tiny size (i think just enough to display minimized scroll bars). What do I mean to add to fix this problem?
    Here is the relavent code:
    public ScenePanel()
         SceneImagePanel sceneImagePanel = new SceneImagePanel("Images/library.jpg");
         JScrollPane sceneScroller = new JScrollPane(sceneImagePanel);
         GridBagLayout gridbag = new GridBagLayout();
         GridBagConstraints c = new GridBagConstraints();
         this.setLayout(gridbag);
         c.insets = new Insets(5,5,5,5);
         JButton b1 = new JButton("Left");
         c.anchor = GridBagConstraints.WEST;
         c.fill = GridBagConstraints.VERTICAL;
         c.gridx = 0;
         c.gridy = 0;
         c.gridwidth = 5;
         c.gridheight = 5;
         c.weightx = 0.5;
         c.weighty = 0.5;
         gridbag.setConstraints(b1, c);
         this.add(b1);
         c.anchor = GridBagConstraints.CENTER;
         c.fill = GridBagConstraints.NONE;
         c.gridx = 5;
         c.gridwidth = 10;
         c.weightx = 0.0;
         c.weighty = 0.0;
         gridbag.setConstraints(sceneScroller, c);
         this.add(sceneScroller);
         JButton b2 = new JButton("Right");
         c.anchor = GridBagConstraints.EAST;
         c.fill = GridBagConstraints.VERTICAL;
         c.gridx = 15;
         c.gridwidth = 5;
         c.weightx = 0.5;
         c.weighty = 0.5;
         gridbag.setConstraints(b2, c);
         this.add(b2);
         JButton b3 = new JButton("Bottom");
         c.anchor = GridBagConstraints.SOUTH;
         c.fill = GridBagConstraints.HORIZONTAL;
         c.gridwidth = 20;
         c.gridx = 0;
         c.gridy = 5;
         c.weighty = -0.5;
         gridbag.setConstraints(b3, c);
         this.add(b3);
    //          this.add(sceneScroller, BorderLayout.CENTER);
    }Note: the commented out line at the end displayed the JScrollPane properly (though I want the scroll pane to be sized to fit its viewport, not its container, so I stopped using BorderLayout)

    Alright, I've figured out why the JScrollPane gets shrunk to such a small size...the 'fill' paramenter of the constraint can't be set to NONE. I've set it to 'BOTH' and changed the other constraints of some other components to fit.
    The problem now is that the scroll pane is too big...the scroll pane does not need to actually have either scroll bar in all cases. To accomidate these situations, I want the scroll pane to only be as large as it needs to be to display as much of its viewport is possible. Meaning, if the viewport does not need the scroll pane to take up as much room as is avaliable to it in the JPanel, the scroll pane should only be as large as needed, and leave empty space around it.
    Here is what I have now:
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    this.setLayout(gridbag);
    c.insets = new Insets(5,5,5,5);
    JButton b1 = new JButton("Left");
    c.anchor = GridBagConstraints.WEST;
    c.fill = GridBagConstraints.VERTICAL;
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 5;
    c.gridheight = 5;
    c.weightx = -0.5;
    c.weighty = 0.5;
    gridbag.setConstraints(b1, c);
    this.add(b1);
    c.anchor = GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.BOTH;
    c.gridx = 5;
    c.gridwidth = 10;
    c.weightx = 0.5;
    gridbag.setConstraints(sceneScroller, c);
    this.add(sceneScroller);
    JButton b2 = new JButton("Right");
    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.VERTICAL;
    c.gridx = 15;
    c.gridwidth = 5;
    c.weightx = -0.5;
    c.weighty = 0.5;
    gridbag.setConstraints(b2, c);
    this.add(b2);
    JButton b3 = new JButton("Bottom");
    c.anchor = GridBagConstraints.SOUTH;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridwidth = 20;
    c.gridx = 0;
    c.gridy = 5;
    c.weighty = -0.5;
    gridbag.setConstraints(b3, c);
    this.add(b3);

  • Is it a bug? GridBagLayout  with textField

    Hi,
    The following method does not work fine.
    The textfield field gets all the space
    but if i change
    JTextField field = new JTextField();
    with
    JPanel field = new JPanel();
    it will work fine.
    I think there is a problem with GridBagLayout
    and textField. is it a bug in jdk1.2
    public JPanel getCPane() {
    int XUNIT = 5;
    int YUNIT = 100;
    JPanel pane = new JPanel();
    JPanel pane1 = new JPanel();
    JTextField field = new JTextField();
    pane1.setBackground(Color.red);
    pane1.setPreferredSize(new Dimension(2*XUNIT, YUNIT));
    field.setPreferredSize(new Dimension(6*XUNIT, YUNIT));
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.insets = new Insets(0,0,0,0);
    c.weightx = c.weighty = 0;
    c.gridx = 0; c.gridy = 0;
    c.gridwidth = 2*XUNIT; c.gridheight = YUNIT;
    pane.add(pane1, c);
    c.weightx = c.weighty = 1;
    c.gridx = 2; c.gridy = 0;
    c.gridwidth = 6*XUNIT; c.gridheight = YUNIT;
    pane.add(field, c);
    return pane;

    Any solution please

  • JScrollpanel Top align problem

    Hi,ALL
    I have a JPanel holds two Objects(JTree and JList);
    So
    The main JPanel is created with FlowLayout.LEFT
    I create two JScrollPanel to hold JTree and JList,
    since JTree is long and JList is short.
    so everytime JList is in the middle of the JScrollPanel.
    I want to align them from top, how to add a Viewport to JScrollPanel from TOP-align, not automatically CENTER-align?
    Thanks in avanced

    At the risk of sounding like the Office Paperclip... it looks like you're writing an explorer.
    If so, use a JSplitPane. Set the left component to a JScrollPane containing a JTree and the right component to a JScrollPane containing a JList.

  • Changing a JLabel text moves everything around -- and it shouldn't

    I have this problem where whenever I call setText() for this one JLabel, it moves everything around. It doesn't have anything to do with the length of the text, because if I replace it with the same exact string, it still moves stuff around.
    I understand it's really hard to troubleshoot these things w/o source code, but I was wondering if this is a problem someone has seen before?
    I'm not going to post my code just because it's too long and I won't ask anyone to go through it for me.
    Basically it is a JFrame with 2 JPanels laid out w/ GridBagLayout, and each JPanel has it's own GridBagLayout
    Thanks

    well, Ironically, while I was creating that code sample thing I figured out what was going on myself. I was confused because of some misdirection--- the issue was not with the JLabel, that was just where the symptoms showed.
    thanks anyway, and sorry for the delayed response -- i only work part time...

  • Question about gridbaglayout

    hi all,
    i am developing an application that is run on windows and unix. my resolution is 800x600 the resolution of the unix box is 1024x768. when i develop the app on my computer using setbounds to place components where i want them to be and then run it on the unix machine the components do not expand to the resolution. will gridbaglayout solve this problem for me or do i need to look at other avenues.
    thanks

    by Design when your resize a Java window, all its components will be resized too.
    You told aboout setBounds... it is not a good deal... Try to use gridBagLayout and set the relathionship between a window components...
    are you using setDimension ??
    yes, GridBagLayout should solve all your problems...
    an example? http://www.lia.ufc.br/~gaucho/Arm/Demo.htm

Maybe you are looking for