1

I'm writing a Chinese Chess program in Java and would much appreciate some guidance on designing/implementing the GUI.

The board is to be divided into a 9x10 grid, with an "image" of the chess piece occupying each cell. The cells also need to be 'registered' when clicked so I know which piece was clicked.

1) I'm thinking GridLayout for the layout manager for the JPanel representing the board. How do I add an image to each component?

public void paintComponent(Graphics g) {
   Image dog = new ImageIcon("dog.png").getImage();
   add(dog)
}

Does not work as dog is not a Component.

2) How would I register for clicks in each cell?

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Vons
  • 3,277
  • 2
  • 16
  • 19

2 Answers2

4

Use a JLabel containing an Icon. Then add the label to the grid layout. Read the Swing tutorial on How to Use Icons for more information.

Also read the section on How to Write a Mouse Listener for listening to clicks on the label.

Or you could use a JButton with an Icon and then use:

button.setBorderPainted(false);

so you don't see the action of clicking the button. Then you would use an ActionListener. The tutorial also has a section on using an ActionListener.

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

Yes, GridLayout seems appropriate for this use.

See the constructor JButton(Icon).

See this answer for an example that carves up an existing image tile set for use in JLabel and JButton instances.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 2
    +1, I was just searching for this example, thinking that the OP who asked the drum question (with transparent circles to play sound) might be able to use something like this. Now, I've book marked the link :0 – camickr Jul 01 '13 at 03:23