Java 为什么必须在paintComponent()内初始化x和y坐标?
练习1609:编写一个程序,使用箭头键绘制线段。当按下向右箭头键、向上箭头键、向左箭头键或向下箭头键时,该线从帧的中心开始向东、北、西或南绘制。简而言之,画一个迷宫。关于我的问题,请参见下面的评论 最后一行Java 为什么必须在paintComponent()内初始化x和y坐标?,java,paintcomponent,Java,Paintcomponent,练习1609:编写一个程序,使用箭头键绘制线段。当按下向右箭头键、向上箭头键、向左箭头键或向下箭头键时,该线从帧的中心开始向东、北、西或南绘制。简而言之,画一个迷宫。关于我的问题,请参见下面的评论 最后一行System.out.println(x+“”+y)输出0,0 但是paintComponent()。在paintcomponent()内部初始化时,输出为292131…这正是我想要的。getWidth()和getHeight()在UI元素通过布局过程之前无法正确设置。这一定会在调用paint
System.out.println(x+“”+y)如果我尝试在其他任何地方初始化x和y,则代码>输出0,0
但是paintComponent()。在paintcomponent()内部初始化时,输出为292131…这正是我想要的。getWidth()
和getHeight()
在UI元素通过布局过程之前无法正确设置。这一定会在调用paintComponent()
之前发生,但可能不会在您尝试调用它们的其他位置发生
见:
如果您需要在设置/更改组件的宽度和高度时收到通知,请查看ComponentListener
:请阅读它可能与getWidth()和getHeight()有关;你能为这些代码提供代码吗?你认为在设置CODRD之前手动验证会解决这个问题吗?你的意思是:“这不是保证的客人……”Vince Emigh:如果我正在解决这个问题,我会考虑把线画在一个单独的“文档”坐标系上,并把它们显示在一个“文档”坐标系上。然后考虑面板上的视图到文档。对于家庭作业来说,这可能是过度的,所以我可能只需要跟踪offsetX/offsetY,并从面板的当前中心绘制到(中心+偏移)。@David Brossard:我不确定你指的是什么。。。也许有些东西已经被编辑或删除了?我按照建议尝试了componentListener。现在一切都好了。只是想让你知道。
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Exercise1609 extends JFrame {
private KeyboardPanel panel = new KeyboardPanel();
public Exercise1609() {
add(panel);
panel.setFocusable(true);
}
public static void main(String[] args) {
Exercise1609 frame = new Exercise1609();
frame.setTitle("Tegn med piltaster");
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//The panel that listens for key and responds by drawing
public static class KeyboardPanel extends JPanel {
private int x,y,previousX,previousY;
private boolean firstTime = true;
public KeyboardPanel() {
/**
* why must x and y be initialized inside paintComponent?
* if I want to start drawing from the middle of the panel?
* If I remove the if-block inside paintComponent and instead
* place the initialization here, as shown with the two lines below:
* x = previousX = getWidth() / 2;
* y = previousY = getHeight() / 2;
* ...then the program will not start to draw from the middle,
* but upper left corner of the screen
*/
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
previousY = y;
previousX = x;
switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN:
y++;
break;
case KeyEvent.VK_UP:
y--;
break;
case KeyEvent.VK_RIGHT:
x++;
break;
case KeyEvent.VK_LEFT:
x--;
break;
}
repaint();
}
});
}//end constructor
@Override
protected void paintComponent(Graphics g) {
super.paintComponents(g);
if(firstTime) {
//Why can't x and y be initialized outiside paintComponent?
//Why can't they be initialized inside the constructor of this class?
x = previousX = getWidth() / 2;
y = previousY = getHeight() / 2;
firstTime = false;
}
g.drawLine(previousX, previousY, x, y);
System.out.println(x + " " + y);
}
}
}