Wednesday, February 8, 2017
This code will draw the 3D board and handle mouse clicks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*; //This is needed for the mouse events
public class SampleGraphicsWindow extends JFrame { //JFrame means "window", in effect
private JPanel wholeWindow; //A JPanel is the content within a window
private int width, height; //For convenience. The drawing area, in pixels.
//Constructor
public SampleGraphicsWindow(int w, int h) {
setTitle("My graphics window");
setSize(w,h);
wholeWindow = new GraphicsPanel(); //GraphicsPanel is defined below
add(wholeWindow);
wholeWindow.addMouseListener(new HandleMouse());
setVisible(true);
}//SampleGraphicsWindow constructor
public static void main(String[] args){
//Simple main program for testing. Just create a window.
SampleGraphicsWindow test = new SampleGraphicsWindow(700,500);
}//main
private class GraphicsPanel extends JPanel {
public void paintComponent(Graphics g){
/* This is where all the drawing commands will go.
* Whenever the window needs to be drawn, or redrawn,
* this method will automatically be called.
*/
//Find out the size of the available area.
Rectangle r = g.getClipBounds();
width = r.width;
height = r.height;
//Just draw two thin diagonal lines. If that works,
//everything else is easy from there.
g.drawLine(0,0,width-1,height-1);
g.drawLine(0,height-1,width-1,0);
//Look for other methods by searching for "Java Graphics class".
//You will always use "g." in front of them.
}//paintComponent method
}//private inner class graphicsPanel
private class HandleMouse implements MouseListener {
//The five standard methods are required. I don't want these ones:
public void mousePressed(MouseEvent e){ /*Do nothing */ }
public void mouseReleased(MouseEvent e){ /*Do nothing */ }
public void mouseEntered(MouseEvent e){ /*Do nothing */ }
public void mouseExited(MouseEvent e){ /*Do nothing */ }
//The only one we really want to pay attention to
public void mouseClicked(MouseEvent e){
System.out.println(e.getX()+","+e.getY());
}//mouseClicked
}//private inner class HandleMouse
}//class SampleGraphicsWindow
Labels:
3D Tic-tac-toe,
Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment