Need a GridBagLayout tutor for dummies please... with working example

199 views Asked by At

I'm trying to create a GUI that has a JXTaskPane, within which an HTML editor pane is showing some lengthy text, then below that are two sliders. One should have the full window width divided 50/50 between the label and the slider, the next slider should have 1/3rd of the width for the label and 2/3 for the slider.

In order for this example to run, you need SwingX, download the jar here.

There are several problems with the code:

  1. On the first startup, the elements are not drawn correctly. The window needs to be resized, or the task pane closed and reopened. Can anyone recommend a way to fix this?
  2. Even though the GridBagConstraint fill parameter is set to use the full horizontal width, the components are only using up about half of the window width and are drawn in the center. How can I make them use the full width and height of the JXTaskPane?
  3. Even though slider2 has its gridwidth property set to 2 (the label has it set to 1) it in fact is drawn narrower than its label! Why does it do that? I tried playing with the weightx parameter, but that just changes the appearance randomly to a little wider or a little narrower, but in what seems to be a random and rather unpredictable fashion. How do I make this label 1/3rd the width of its slider?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import org.jdesktop.swingx.JXTaskPane;

class test {
  public static void main(String[] arg) {
    JFrame mainWindow = new JFrame();
    JXTaskPane taskPane = new JXTaskPane();
    JSlider slider1 = new JSlider(0,100,50);
    JSlider slider2 = new JSlider(0,100,50);

    taskPane.setCollapsed(false);

    // slider 1 with its label in a simple GridLayout
    JPanel pnlSlider1 = new JPanel();
    pnlSlider1.setLayout(new GridLayout(1,1));  // 1 row, 1 column
    pnlSlider1.add(new JLabel("Description for slider1"));
    pnlSlider1.add(slider1);

    // slider 2 with its label is in a GridBagLayout, the label should be 1/3 of the width of the slider
    JPanel pnlSlider2 = new JPanel();
    pnlSlider2.setLayout(new GridBagLayout());
    GridBagConstraints c2 = new GridBagConstraints();
    c2.fill = GridBagConstraints.HORIZONTAL;
    c2.gridx = 0;
    c2.gridy = 0;
    c2.gridwidth = 1;
    c2.weighty = 1;
    c2.weightx = 1;
    pnlSlider2.add(new JLabel("Description for slider2"), c2);
    c2.gridx = 1;
    c2.gridwidth = 2;
    c2.weightx = 1;
    pnlSlider2.add(slider2, c2);

    // label should now be to the left of slider

    String content = "<html>Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content ";
    content += "Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content";
    content += "Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content </html>";
    JEditorPane ep = new JEditorPane("text/html", content);

    // this is the main window panel
    //JPanel panel = new JPanel();
    taskPane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    taskPane.add(ep, c);
    c.gridy = 1;
    taskPane.add(pnlSlider1, c);
    c.gridy = 2;
    c.insets = new Insets(10,0,0,0);
    taskPane.add(pnlSlider2, c);

    // tie it all together and display the window
        mainWindow.setPreferredSize(new Dimension(600, 600));
        mainWindow.setLocation(100, 100);
        mainWindow.getContentPane().add(taskPane);
        mainWindow.pack();
        mainWindow.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        mainWindow.setVisible(true);

  }
}
1

There are 1 answers

0
Madhan On

BorderLayout is easier to design when compared to GridBagLayout. Hope this is what you've asked for.I've used Netbeans to create the layout and then added it to the JXTaskPane

import org.jdesktop.swingx.JXTaskPane;
import org.jdesktop.swingx.JXTaskPaneContainer;


public class NewJFrame extends javax.swing.JFrame {

/**
 * Creates new form NewJFrame
 */
public NewJFrame() {
    initComponents();
    initTaskPane();
    setLocationRelativeTo(null);
}

private void initTaskPane() {
    JXTaskPaneContainer taskpanecontainer = new JXTaskPaneContainer();
    JXTaskPane taskPane = new JXTaskPane();
    taskPane.setLayout(new java.awt.BorderLayout());
    taskPane.add(contentPanel, java.awt.BorderLayout.CENTER);
    taskPane.setCollapsed(false);
    taskpanecontainer.add(taskPane);
    this.setContentPane(taskpanecontainer);
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    contentPanel = new javax.swing.JPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jEditorPane1 = new javax.swing.JEditorPane();
    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jSlider1 = new javax.swing.JSlider();
    jLabel2 = new javax.swing.JLabel();
    jSlider2 = new javax.swing.JSlider();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setPreferredSize(new java.awt.Dimension(400, 500));

    contentPanel.setLayout(new java.awt.BorderLayout());

    jScrollPane1.setPreferredSize(new java.awt.Dimension(108, 400));

    jEditorPane1.setContentType("text/html"); // NOI18N
    jEditorPane1.setText("<html>\r\n Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content.Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content.Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content.Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content.Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content.Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content Some rather long winded HTML content.\n</html>\r\n");
    jScrollPane1.setViewportView(jEditorPane1);

    contentPanel.add(jScrollPane1, java.awt.BorderLayout.CENTER);

    jLabel1.setText("Description for Slider1");

    jLabel2.setText("Description for Slider2");

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSlider1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSlider2, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)))
            .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jSlider1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jSlider2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap())
    );

    contentPanel.add(jPanel1, java.awt.BorderLayout.SOUTH);

    getContentPane().add(contentPanel, java.awt.BorderLayout.CENTER);

    pack();
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JPanel contentPanel;
private javax.swing.JEditorPane jEditorPane1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSlider jSlider1;
private javax.swing.JSlider jSlider2;
// End of variables declaration                   
}

Output

enter image description here