So I have this code:
package tictactoe;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TicTacToe extends JFrame {
public static void main(String[] args) {
JFrame masterFrame = new JFrame("TicTacToe");
JPanel drawingPanel = new JPanel();
GameBoard theGame = new GameBoard();
masterFrame.add(drawingPanel);
masterFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
masterFrame.setSize(504, 504);
masterFrame.setResizable(false);
masterFrame.setLocationRelativeTo(null);
masterFrame.setVisible(true);
} //End of Main method
@Override
public void paint (Graphics g) {
Graphics2D g2 = (Graphics2D) g;
//Drawing the GridLines
g2.drawLine(168, 0, 168, 500);
g2.drawLine(336, 0, 336, 500);
g2.drawLine(0, 168, 500, 168);
g2.drawLine(0, 336, 500, 336);
} //End of Paint Method
} //End of TicTacToe Class
What I would like it to do is draw 4 lines onto my JFrame in a TicTacToe fashion, but the JFrame remains blank. Why is this? What is wrong with my code and how should I fix it?
Had you actually created an instance of
TicTacToe
, instead ofJFrame
, yourDrawingPane
would likely be painting over/covering what ever your frame is painting via it'spaint
method.A child component can be painted without notifying or requiring it's parent container to be painted, meaning that the child components will actually cover up what has previously been painted by the frame, this can produce some very weird results, as different parts get updated
A
JFrame
contains a number of child components, including theJRootPane
and thecontentPane
, onto which you place your own components.A better solution in your case is probably to use your
DrawingPane
and customise it'spaintComponent
to render the gridSee Painting in AWT and Swing and Performing Custom Painting for more details
For example...
As a general rule, it's recommended not to extend directly from
JFrame
, apart from the custom painting issues you're having, you're not adding any functionality to the class and you're locking yourself into a single use case (it'd be hard to re-use the class again)