Search code examples
javaswingjpaneljlabel

Moving a JLabel for a game


I am coding a Backgammon game that plays by itself. While the backend code is mostly done, me and my colleague have pretty much no experience in GUI coding. We used the Designer given by a plugin for Eclipse and most of the code was generated.

So here's the thing. Right now there is a JFrame which has a JPanel in which are 2 JLabels, one for the background and one for 1 playing piece (when I figure this out, the rest of them will be added). These are all in an initialize() method which is run through EventQueue.invokeLater(new Runnable()). After the board and the piece are drawn, the startGame() method is called, which finally comes to a method called movePiece(), with the sole purpose of moving that JLabel piece I talked about before.

I have tried mostly everything I can think of, I have scoured the forums and only found people talking about layouts (which I may or may not be using, as I said, generated code) and the darn JLabel won't move when I call setLocation() inside the movePiece() method. It always throws a NullPointerException at that line which is bizarre because the image is already drawn. I will include part of the code below. I know this will probably look like some of the worse codes ever, but please bear with my lack of skill and help me make this better. Any insights?

public class Main{

public JLabel image1;

private JFrame frame;


/**
 * Launch the application.
 */
public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {

        public void run() {
            try {

                Main window = new Main();

                window.frame.setVisible(true);
                new Main(1);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
public Main() {
    initialize();

}

public Main(int i){
    startGame();
}

public void startGame() {
    //game code
    movePiece(Move.getPos(), Move.getDest());
    //rest of code
}

public void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 1023, 617);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setPreferredSize(new Dimension(800, 700));

    JPanel panel_1 = new JPanel();
    panel_1.setPreferredSize(new Dimension(200, 700));
    frame.getContentPane().add(panel_1, BorderLayout.EAST);

    JButton btnNewButton = new JButton("Start Game");

    /* ACTION LISTENER FOR THE BUTTON */

    btnNewButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {
        }
    });

    btnNewButton.setFocusable(false);
    btnNewButton.setForeground(SystemColor.windowBorder);
    btnNewButton.setBackground(SystemColor.menu);
    btnNewButton.setVerifyInputWhenFocusTarget(false);
    btnNewButton.setRequestFocusEnabled(false);
    btnNewButton.setRolloverEnabled(false);
    btnNewButton.setFont(new Font("Verdana", Font.PLAIN, 11));
    btnNewButton.setDebugGraphicsOptions(DebugGraphics.NONE_OPTION);

    /* ADDING THE BTN TO PANEL 1 TO THE RIGHT */
    panel_1.add(btnNewButton);
    JPanel parentPanel = new JPanel();
    parentPanel.setFocusable(false);
    parentPanel.setEnabled(false);
    parentPanel.setDoubleBuffered(false);
    parentPanel.setDebugGraphicsOptions(DebugGraphics.NONE_OPTION);
    parentPanel.setIgnoreRepaint(true);
    parentPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
    parentPanel.setBorder(null);
    parentPanel.setPreferredSize(new Dimension(800, 700));
    parentPanel.setBackground(SystemColor.menu);

    frame.getContentPane().add(parentPanel, BorderLayout.WEST);

    /* BACKGAMMON BOARD LABEL-->PANEL */
    ImageIcon imageIcon = new ImageIcon(
            new ImageIcon("images/bg.png").getImage()
                    .getScaledInstance(800, 551, Image.SCALE_SMOOTH));
    parentPanel.setLayout(null);
    ImageIcon imageIcon1 = new ImageIcon(
            new ImageIcon("images/pl.png").getImage()
                    .getScaledInstance(50, 50, Image.SCALE_SMOOTH));

    image1 = new JLabel("");
    image1.setBounds(37, 36, 50, 50);
    parentPanel.add(image1);
    image1.setIcon(imageIcon1);



    JLabel bg = new JLabel("");
    bg.setBounds(10, 11, 800, 551);
    bg.setIcon(imageIcon);
    parentPanel.add(bg);
}

void movePiece(int pos, int dest) {
    //null exception happens here, ignore the arguments
    image1.setLocation(37 + 50,36);

}

Solution

  • You create an instance of Main and make it visible...

    Main window = new Main();
    window.frame.setVisible(true);
    

    You then create a new instance of Main, which, through it's constructor, calls your moviePiece method...

    new Main(1);
    

    But the new instance of Main has nothing to do with the previous instance or any of the components which they created.

    Instead, trying doing...

    window.movePiece(Move.getPos(), Move.getDest());
    

    instead of new Main(1);