很简单的问题,但我不能这样做.我有3个班:
DrawCircle 类
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class DrawCircle extends JPanel
{
private int w, h, di, diBig, diSmall, maxRad, xSq, ySq, xPoint, yPoint;
public DrawFrame d;
public DrawCircle()
{
w = 400;
h = 400;
diBig = 300;
diSmall = 10;
maxRad = (diBig/2) - diSmall;
xSq = 50;
ySq = 50;
xPoint = 200;
yPoint = 200;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.blue);
g.drawOval(xSq, ySq, diBig, diBig);
for(int y=ySq; y<ySq+diBig; y=y+diSmall*2)
{
for(int x=xSq; x<w-xSq; x=x+diSmall)
{
if(Math.sqrt(Math.pow(yPoint-y,2) + Math.pow(xPoint-x, 2))<= maxRad)
{
g.drawOval(x, y, diSmall, diSmall);
}
}
}
for(int y=ySq+10; y<ySq+diBig; y=y+diSmall*2)
{
for(int x=xSq+5; x<w-xSq; x=x+diSmall)
{
if(Math.sqrt(Math.pow(yPoint-y,2) + Math.pow(xPoint-x, 2))<= maxRad)
{
g.drawOval(x, y, diSmall, diSmall);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
DrawFrame 类
public class DrawFrame extends JFrame
{
public DrawFrame()
{
int width = 400;
int height = 400;
setTitle("Frame");
setSize(width, height);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
Container contentPane = getContentPane();
contentPane.add(new DrawCircle());
}
}
Run Code Online (Sandbox Code Playgroud)
CircMain 类
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CircMain
{
public static void main(String[] args)
{
JFrame frame = new DrawFrame();
frame.show();
}
}
Run Code Online (Sandbox Code Playgroud)
一个类创建一个框架,另一个类绘制一个圆圈并用较小的圆圈填充它.在DrawFrame我设置宽度和高度.在DrawCircle我需要访问的宽度和高度DrawFrame.我该怎么做呢?
我试着做一个对象,并尝试使用.getWidth和.getHeight,但不能让它开始工作.我需要特定的代码,因为我已经尝试了很多东西,但无法让它工作.我在宣布宽度和高度错误DrawFrame吗?我在错误的方式创建对象DrawCircle?
另外,我使用的变量DrawCircle,是否应该在构造函数中使用它们?
Pet*_*ter 44
您可以将变量设为公共字段:
public int width;
public int height;
DrawFrame() {
this.width = 400;
this.height = 400;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以像这样访问变量:
DrawFrame frame = new DrawFrame();
int theWidth = frame.width;
int theHeight = frame.height;
Run Code Online (Sandbox Code Playgroud)
但是,更好的解决方案是使变量private字段为您的类添加两个访问器方法,从而保持DrawFrame类中的数据封装:
private int width;
private int height;
DrawFrame() {
this.width = 400;
this.height = 400;
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样得到宽度/高度:
DrawFrame frame = new DrawFrame();
int theWidth = frame.getWidth();
int theHeight = frame.getHeight();
Run Code Online (Sandbox Code Playgroud)
我强烈建议你使用后一种方法.
小智 5
我有同样的问题。为了修改来自不同类的变量,我使它们扩展了要修改的类。我还将超类的变量设为静态,以便可以通过继承它们的任何方式对其进行更改。我还对它们进行了保护以提高灵活性。
资料来源:糟糕的经历。良好的教训。