I am trying to draw to my JFrame with Graphics. For some reason, it won't draw anything. What am I doing wrong? I have added my paint method, imported everything. Am I placing the method in the wrong place?
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
public class Main extends Canvas implements MouseListener, KeyListener {
public int WIDTH = 1080;
public static Main main;
public boolean playing = false;
public Main() {
addMouseListener(this);
addKeyListener(this);
JFrame frame = new JFrame("Clicker");
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(50, 50, 100, 100);
}
public static void main(String[] args) {
main = new Main();
}
public void MainScreen() {
}
@
Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@
Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@
Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@
Override
public void mouseClicked(MouseEvent evt) {
// TODO Auto-generated method stub
}
@
Override
public void mouseEntered(MouseEvent evt) {
// TODO Auto-generated method stub
}
@
Override
public void mouseExited(MouseEvent evt) {
// TODO Auto-generated method stub
}
@
Override
public void mousePressed(MouseEvent evt) {
// TODO Auto-generated method stub
}
@
Override
public void mouseReleased(MouseEvent evt) {
// TODO Auto-generated method stub
}
}
Try to extend from the JFrame
class instead of the Canvas
class:
public class Main extends JFrame implements ...
You also have to edit your constructor then like:
public Main() {
super("Clicker");
addMouseListener(this);
addKeyListener(this);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.