【发布时间】:2016-08-27 08:29:23
【问题描述】:
我正在创建一个需要画线和点的游戏。我有一个名为paintDot 的通用函数(检查下面的代码),我想在不同的函数中调用它。我不知道怎么称呼它,有帮助吗?
public void paintDot (Graphics g, int x, int y)
{
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillOval(x,y,15,15);
}
这是我需要调用绘图函数的另一个函数/方法: ATM 坐标只是硬编码的,所以我知道它工作正常。
如您所见,我调用 paintDot 方法时争论不休。不知道应该在Graphics g提出什么论点
private void gameWindow (int dif)
{
this.removeAll();
areaImage = new JPanel ();
//distance between points = 75
//point grid = 7*6
areaImage.setBounds(50,50,675,600);
areaImage.setBackground(Color.WHITE);
areaImage.setBorder(BorderFactory.createLineBorder(Color.black));
add(areaImage);
answer = new JTextField();
answer.setBounds(835,200,150,50);
answer.setBorder(BorderFactory.createLineBorder(Color.black));
answer.setHorizontalAlignment(JTextField.CENTER);
answer.setFont(new Font("Verdana", Font.BOLD, 20));
add(answer);
info= new JLabel ("Write your answer here:");
info.setBounds(830,155,250,50);
info.setFont(new Font("Verdana", Font.BOLD, 12));
add(info);
checkAnswer = new JButton ("Check Answer");
checkAnswer.setBounds(835,310,150,50);
checkAnswer.addActionListener(this);
add(checkAnswer);
next = new JButton ("Next");
next.setBounds(835,410,150,50);
next.addActionListener(this);
add(next);
end = new JButton ("End Game");
end.setBounds(835,510,150,50);
end.addActionListener(this);
add(end);
revalidate();
repaint();
int x = 75,y=75;
for(int num=0;num<6;num++)
{
for(int xx=0; x<7;xx++)
{
paintDot (areaImage,x,y); // here is the problem
x=x*2;
}
y=y*2;
}
}
【问题讨论】:
-
基本上我需要做一个点网格(见上面代码中的注释)
-
1) 为了尽快获得更好的帮助,请发帖 minimal reproducible example 或 Short, Self Contained, Correct Example。 2) Java GUI 必须在不同的语言环境中使用不同的 PLAF 在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
-
解决此类问题的基本方法是创建一个
Dot类,该类知道如何(以及在何处)绘制自己。维护一个点的集合或数组。在paintComponent(Graphics)方法中,迭代列表,调用Dot.draw(Graphics)方法依次绘制。