Question

I'm using a JLabel to notify the user if there's an error with his/her input inside a JTextField.

If there's a problem, I'm setting the text of the JLabel to "invalid input". However, when the text in the label is set, it slightly 'pushes' the rest of the layout a little. I want everything to stay in it's place. Any ideas?

public Dialog(Window owner){

    widthL = new JLabel("Width: ");
    heightL = new JLabel("Height: ");
    widthF = new JTextField(5);
    heightF = new JTextField(5);
    apply = new JButton("Apply");
    error = new JLabel("");

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.insets = new Insets(10,10,10,10);

    gbc.gridy = 1;

    gbc.gridx = 1;
    add(widthL,gbc);

    gbc.gridx = 2;
    add(widthF,gbc);

    gbc.gridy = 2;

    gbc.gridx = 1;
    add(heightL,gbc);

    gbc.gridx = 2;
    add(heightF,gbc);

    gbc.gridy = 1;
    gbc.gridx = 3;
    gbc.gridheight = 2;
    add(apply,gbc);

    gbc.gridheight = 1;
    gbc.gridy = 3;
    gbc.gridx = 2;
    add(error,gbc);

    apply.addActionListener(this);

    setVisible(true);

}

public void actionPerformed(ActionEvent e) {

    int width,height;

    try{
        width = Integer.parseInt(widthF.getText());
        height = Integer.parseInt(heightF.getText());
    }catch(NumberFormatException ex){
        error.setText("Invalid input");
    }

}

No correct solution

OTHER TIPS

Since you didn't privide a Minimal, Complete, Tested, and Readable example that demonstrates the problem, I only glanced enough to see that you were using GridBagLayout.

Some techniques that you could use:

  1. Somewhere in the same column as your label (either just above or just below), you can put a Box.createHorizontalStrut(...) component that's just long enough to be longer than any anticipated length for your JLabel. Of course, you'd need to know the longest text ahead of time (and calculate its width in a JLabel) for this to work.

  2. Put your JLabel on it's own line so as not to disturb the placement of other components on the same line. You'd want to make sure it has a gridwidth that will span multiple columns so as not to make the column of the JLabel expand for the rest of your layout.

  3. Use HTML in your JLabel to define a fixed width in pixels.

  4. Create a multilined JLabel using HTML with <br> tags.

  5. Create a JTextField and decorate it accordingly (opacity, border, non-editable, etc.) so that it looks like a JLabel.

  6. Just put your messages in a JTextArea since JLabels aren't really well-suited for dynamic, arbitrary text. You'll likely have layout problems ;-)

  7. If "invalid input" is the only text that will ever be there for the label, preset the text on the JLabel, and then just call label.setVisible(true/false) when appropriate.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top