我是个java新手,我想做一个在屏幕上画一个方框的程序,除了paintComponent()没有用之外,其他的都是正确的。
import java.awt.*;
import javax.swing.*;
import java.awt.Graphics2D.*;
public class Frame extends JPanel
{
@Override //this section creates the box
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawRect(150,150,20,20);
}
public static void createWindow() //this section creates the frame
{
JFrame frame = new JFrame("Simple GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set closing bebavior
frame.setSize(400, 400); //set the size of jframe
frame.setLocationRelativeTo(null); //center the jframe
frame.setVisible(true); //show the frame
}
//main method
public static void main(String[] args)
{
createWindow();//launch your creaWindow method
paintComponent();
}
} 发布于 2020-10-21 12:58:07
您必须复习Java的基础知识。您的错误在于,您必须创建此类框架的对象,并将其添加到已创建的JFrame中。下面是正确的代码@Hh000。
import java.awt.*;
import javax.swing.*;
import java.awt.Graphics2D.*;
public class Frame extends JPanel{
@Override //this section creates the box
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawRect(150,150,20,20);
}
//main method
public static void main(String[] args){
JFrame frame = new JFrame("Simple GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set closing bebavior
Frame frameObject = new Frame(); //Making a class object
frame.add(frameObject); //Adding the object into the JFrame
frame.setSize(400, 400); //set the size of jframe
frame.setLocationRelativeTo(null); //center the jframe
frame.setVisible(true);
}
}https://stackoverflow.com/questions/64456831
复制相似问题