1

Edit: When I start the program, the chessboard gets drawn as it's suppose to and the button works. But I want the chessboard to be drawn only when I push the button, not when I run the program. How can I do that ?

import javax.swing.*;        
import java.awt.*;
import java.awt.event.*;

public class Male extends JFrame implements ActionListener {      
JFrame frame;
JPanel DrawPanel;
JButton button;


public void Male() {
frame = new JFrame();
button = new JButton("MALE");
button.addActionListener(this);

MyDrawPanel DrawPanel = new MyDrawPanel();


frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, DrawPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
frame.setSize(500,500);
frame.setVisible(true);

}


public static void main(String[] args) {
  Male gui = new Male();
  gui.Male();

}
public void actionPerformed(ActionEvent event) {
    frame.repaint();

}
}

class MyDrawPanel extends JPanel {    

public void paintComponent(Graphics g) {
  g.setColor(Color.BLACK);
  setBackground(Color.WHITE);
  int x=0;
  int y=0;

  for (int i=0; i<32; i++){
     g.fillRect(x, y, 50, 50);
     x = x + 100;

     if (x == 400){
     x = 50;
     y = y + 50;
     }else if (x == 450){
     x = 0;
     y = y + 50;
  }
  }

}   
}
Deli Irium
  • 45
  • 1
  • 5
  • 3
    *"Here is the code with blanks to fill:"* So get started. Get back to us when you can ask a *specific* question. – Andrew Thompson Jan 15 '13 at 12:44
  • I'm not asking anyone to simply fill in the blanks for me. I'd like to know if I should make the JButton which will do the drawing in the class MaleFrame and where should I put the Main method, because eclipse won't compile without it. I would put it in the class Male but there's no room so where could I put it ? – Deli Irium Jan 15 '13 at 12:53
  • OK *"How to make a button paint in Java?"* On `actionPerformed(ActionEvent)`, call `repaint()` on the custom component. – Andrew Thompson Jan 15 '13 at 12:59
  • So I updated my code and have a more specific question now. Any help ? – Deli Irium Jan 15 '13 at 14:09
  • have a look at http://stackoverflow.com/questions/2158/creating-a-custom-button-in-java – Rachel Gallen Jan 15 '13 at 15:21

1 Answers1

0

The way I would do it is put the bit that draws the board in an if statement and make a boolean variable that is set to true when the button is clicked.

For example:

 if(hasBeenPressed){
     // add drawing code here
 }

I'm not really familiar with buttons in java so I can't really tell you how to set it up fully, but I hope this helps you at least a bit in doing what you want to do.

H3XXX
  • 595
  • 1
  • 9
  • 22