-1

After a lot of research I only could get that board image with using label. Now I cannot change it's position. I tried a lot of functions. What is the exact function do I need

public class Board extends JFrame {
    private ImageIcon image;
    private JLabel label;

    public Board() {
        image = new ImageIcon(getClass().getResource("board.png"));
        label = new JLabel(image);
        label.setLocation(200, 0);  //This is the one that I expected to do the thing
        add(label);
    }

    public static void main(String [] args) {
        Board b = new Board();
        b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        b.setVisible(true);
        b.setSize(1280, 1000);
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Mehr
  • 170
  • 1
  • 1
  • 8

2 Answers2

2

Don't try to manually set the location of a component. Swing was designed to be used with layout managers. Read the section from the Swing tutorial on Using Layout Managers for more information.

One way to position a component is to give the component a Border. So you could do something like:

label.setBorder( new EmptyBorder(200, 0, 0, 0) );

The tutorial also has a section on How to Use Borders.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

First of all: you shouldn't move components manually. This should be left to the layoutmanager. But you can. The basic problem you're facing is - or atleast i think so - : you're board still has an layoutmanager set, which will continue to layout the board and due to this aswell move (and handle the size of) you're component. Just call setLayout(null); before positioning the label and specify the size and it should work.

  • When I add the setLayout(null) my image had gone. I couldn't see my image. So I am not using it. Still thanks. – Mehr Mar 13 '15 at 19:31
  • Oops, sry, i forgot about that: the layoutmanager aswell handles the size of the components. Since you're layoutmanager is gone, you'll have to do this aswell. Set the size of you're board and everything should be fine –  Mar 13 '15 at 19:48
  • Oh! It got better now. I am gonna use yours. Somehow I feel that it is better :) – Mehr Mar 13 '15 at 19:53