簡體   English   中英

getHeight()和getWidth()對於繪制半圓返回0

[英]getHeight() and getWidth() return 0 for drawing semicircles

我正在嘗試制作一個gui應用程序,該應用程序在由用戶運行時顯示彩虹。 無論出於何種原因,半圓都不會出現在窗口中。 我做了一個調試方法,它顯示x和y均為0。有人可以告訴我這是怎么回事嗎?

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Rainbow extends JPanel
{
   // Declare skyColor:
  static Color skyColor = Color.CYAN;

public Rainbow()
{
setBackground(skyColor);
}

  // Draws the rainbow.

public void paintComponent(Graphics g)
{
super.paintComponent(g);
int width = getWidth();    
int height = getHeight();

// Declare and initialize local int variables xCenter, yCenter
// that represent the center of the rainbow rings:
int xCenter = (1/2)*width;
int yCenter = (3/4)*height;
// Declare and initialize the radius of the large semicircle:
int smallRadius = height/4;
int largeRadius = width/4;
int mediumRadius = (int) Math.sqrt(smallRadius * largeRadius);
g.setColor(Color.RED);
g.fillArc(xCenter - largeRadius/2,yCenter - largeRadius/2 + largeRadius/4 -height/4,largeRadius,largeRadius,0,180);
// Draw the large semicircle:

// Declare and initialize the radii of the small and medium
// semicircles and draw them:
g.setColor(Color.GREEN);
g.fillArc(largeRadius+mediumRadius/2, yCenter-(largeRadius+mediumRadius)/2, mediumRadius, mediumRadius, 0, 180);    
g.setColor(Color.MAGENTA);
g.fillArc(largeRadius+smallRadius/2, yCenter-(largeRadius+smallRadius)/2, smallRadius, smallRadius, 0, 180);      // Calculate the radius of the innermost (sky-color) semicircle
debug(xCenter,yCenter,smallRadius,largeRadius,mediumRadius);
// Draw the sky-color semicircle:
// ________________________________________________
}
public static void debug(int x,int y,int r1,int r2,int r3)
{
System.out.println("xCenter is " + x + ".");
System.out.println("yCenter is " + y + ".");
System.out.println("smallRadius is " + r1 + ".");       
System.out.println("largeRadius is " + r2 + ".");  
System.out.println("mediumRadius is " + r3 + ".");  
}
public static void main(String[] args)
{
  JFrame w = new JFrame("Rainbow");
  w.setBounds(300, 300, 300, 200);
  w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  Container c = w.getContentPane();
  c.add(new Rainbow());
  w.setVisible(true);
}
}

問題在這里:

int xCenter = (1/2)*width;   // this division truncates decimals, returns 0
int yCenter = (3/4)*height;

嘗試這個:

int xCenter = (int)((1.0/2)*width);  // this division preserves decimals
int yCenter = (int)((3.0/4)*height);

甚至更簡單:

int xCenter = (int)(0.5*width);
int yCenter = (int)(0.75*height);

您正在執行整數除法,該表達式: 1/2返回0 ,任何數字乘以0就是0

您正在做int除法。 1/2和3/4均為0。取而代之的是進行雙除法,並將其強制轉換為int,或者對您的示例更好,在除法之前先將分子乘以。

例如,代替:

int xCenter = (1/2)*width;
int yCenter = (3/4)*height;

做:

// No need to cast!
int xCenter = width / 2;
int yCenter = (3 * height) / 4;

暫無
暫無

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

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