尝试在 Java 上使用基本的 swing 总是给我带来问题。 当运行时创建 JFrame 时,最初没有绘制任何组件,您显然必须调整窗口大小才能调用 paint() 吗?有没有我遗漏的简单解决方法?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class LabTen extends JFrame{
int x, y;
public LabTen(){
this.setSize(200,200);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().add(new Board()); //do this in the constructor
}
public static void main(String[] args){
LabTen one = new LabTen();
one.repaint();
}
}
//mouseListener has more things when we're going in and out so you should have it too
//write on the component or pannel, not the frame
class Board extends JComponent implements MouseListener, MouseMotionListener{
int mouseX, mouseY;
public Board(){
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent e){
this.mouseX = e.getX();
this.mouseY = e.getY();
this.repaint();
}
public void mouseDragged(MouseEvent e){
//do nothing...
}
public void mouseClicked(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
public void paintComponent(Graphics g){
//g.drawString("(" + this.mouseX + ", " + this.mouseY + ")", this.mouseX,this.mouseY);
//this uses the default way
// g.drawLine(this.getWidth()/2, this.getHeight()/2, this.mouseX, this.mouseY);
double distance = Math.sqrt(Math.pow(this.mouseX - this.getWidth()/2, 2) + Math.pow(this.mouseY - this.getHeight()/2, 2));
int centerX = this.getWidth()/2;
int centerY = this.getHeight()/2;
for(int i = 0; i < 20; i++){
double distanceX =
g.drawLine(centerX, centerY, (centerX))
}
}
}
最佳答案
您的顺序完全错误。这样做:
添加组件
this.add(new Board());
设置首选大小
this.setPreferredSize(new Dimension(200, 200));
打包框架
this.pack();
设置框架可见。
this.setVisible(true);
当然,this
就是您的 JFrame。
关于java - Mac OS X Java 最初不绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8000073/