我有三个类 - TableApp/Diner/TablePanel。我不太明白图形类是如何工作的。我需要从我的 main 方法向我的paintComponent 发送一个 Graphics 对象引用,但我不确定如何将它链接在一起。任何关于如何如此有帮助的解释!
TableApp 类
import javax.swing.*;
public class TableApp{
public static void main(String[]args){
JFrame frame = new JFrame();
TablePanel table = new TablePanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(500,500); //I dont understand how to send my paintComponent a reference of a Graphics object
}
}
表面板类
import java.awt.*;
import javax.swing.*;
public class TablePanel extends JPanel{
Diner diner1,diner2,diner3,diner4,diner5,diner6;
public TablePanel(){
diner1 = new Diner(50,50,300,1,"Murray",Color.blue);
diner2 = new Diner(50,50,300,1,"Murray",Color.blue);//will change once program runs
diner3 = new Diner(50,50,300,1,"Murray",Color.blue);
diner4 = new Diner(50,50,300,1,"Murray",Color.blue);
diner5 = new Diner(50,50,300,1,"Murray",Color.blue);
diner6 = new Diner(50,50,300,1,"Murray",Color.blue);
setPreferredSize(new Dimension(300,200));
setBackground(Color.white);
}
public void paintComponent(Graphics g){//need call from main
super.paintComponent(g);
diner1.draw(g);
diner2.draw(g);
diner3.draw(g);
diner4.draw(g);
diner5.draw(g);
diner6.draw(g);
}
}
晚餐班
import java.awt.*;
import javax.swing.*;
public class Diner{
private int X,Y,diameter=50,seatNumber;
private String name;
private Color colour;
public Diner(int x,int y,int d,int sN,String n,Color col){//construct
X=x;
Y=y;
name=n;
diameter=d;
name=n;
colour=col;
}
public void draw(Graphics g){
g.setColor(Color.blue);
g.fillOval(X,Y,diameter,diameter);
}
}