简体   繁体   English

Mac OS X Java最初并未绘制

[英]Mac OS X Java doesn't draw initially

Trying to work with basic swing on Java keeps giving me issues. 尝试使用Java的基本功能总是给我带来问题。 When the JFrame is created by the runtime, none of the components are drawn initially, you have to resize the window to invoke paint() apparently? 当运行时创建JFrame时,最初没有绘制任何组件,您是否必须调整窗口大小才能明显调用paint()? Is there a simple fix to this that I'm missing? 有没有我所缺少的简单解决方法?

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))
        }           
    }
}

You are doing it completely the wrong order. 您完全按照错误的顺序进行操作。 Do it this way: 这样做:

  1. Add the component 添加组件

     this.add(new Board()); 
  2. Set the preferred size 设置首选尺寸

     this.setPreferredSize(new Dimension(200, 200)); 
  3. Pack the frame 包装框架

     this.pack(); 
  4. Set the frame visible. 将框架设置为可见。

     this.setVisible(true); 

Of course, this is your JFrame. 当然, this是您的JFrame。

设置完JFrame ,您应该调用jFrame.pack()jFrame.setVisible(true)

实现之前,所有组件都需要添加到容器中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM