Pergunta

I want to position my image which I have placed inside a JLabel. Here is my code:

public Main() {
    setLayout (new FlowLayout());
            image = new ImageIcon(getClass().getResource("title.gif"));
            image1 = new JLabel(image);
            image1.setAlignmentX(400);
            image1.setAlignmentY(400);
            add(image1);
}

It displays the image, but the lines

image1.setAlignmentX(400);
image1.setAlignmentY(400);

Do not do anything. I'm new to Java, any help appreciated.

(I would appreciate an example.)

Foi útil?

Solução

Issues:

  • You're using FlowLayout which won't respect absolute positioning even if you were doing it correctly.
  • setAlignmentX(...) is for suggesting to the container the component's alignment along the x-axis. As noted above, it takes a float number from 0.0f to 1.0f, with 0f meaning alignment to the left, 0.5f centered, and 1.0f to the right. You definitely do not want to use this method or it's y counterpart here.
  • Absolute positioning requires a container that uses a null layout, not FlowLayout.
  • Absolute positioning is done via the setBounds(...) or the setLocation(...) method.
  • Having said this, I suggest that you don't try to position things absolutely unless there's an absolute need, and there's a good chance here that you don't, that there's a better way.

Please tell us more of the details of your problem, not how you're trying to solve it, and we'll probably be able to help you better.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top