簡體   English   中英

Mac OS X Java最初並未繪制

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

嘗試使用Java的基本功能總是給我帶來問題。 當運行時創建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))
        }           
    }
}

您完全按照錯誤的順序進行操作。 這樣做:

  1. 添加組件

     this.add(new Board()); 
  2. 設置首選尺寸

     this.setPreferredSize(new Dimension(200, 200)); 
  3. 包裝框架

     this.pack(); 
  4. 將框架設置為可見。

     this.setVisible(true); 

當然, this是您的JFrame。

設置完JFrame ,您應該調用jFrame.pack()jFrame.setVisible(true)

實現之前,所有組件都需要添加到容器中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM