gpt4 book ai didi

java - 从另一个类访问变量

转载 作者:IT老高 更新时间:2023-10-28 21:12:02 27 4
gpt4 key购买 nike

很简单的问题,但我做不到。我有 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);
}
}
}
}
}

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

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

一个类创建一个框架,另一个类绘制一个圆圈并用较小的圆圈填充它。在 DrawFrame 我设置宽度和高度。在 DrawCircle 中,我需要访问 DrawFrame 的宽度和高度。我该怎么做?

我尝试制作一个对象并尝试使用 .getWidth.getHeight 但无法让它工作。我在这里需要特定的代码,因为我尝试了很多东西但无法让它工作。我是否在 DrawFrame 中声明宽度和高度错误?在 DrawCircle 中以错误的方式创建对象吗?

另外,我在 DrawCircle 中使用的变量,我是否应该将它们放在构造函数中?

最佳答案

您可以将变量设为公共(public)字段:

  public int width;
public int height;

DrawFrame() {
this.width = 400;
this.height = 400;
}

然后您可以像这样访问变量:

DrawFrame frame = new DrawFrame();
int theWidth = frame.width;
int theHeight = frame.height;

然而,更好的解决方案是让变量私有(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;
}

然后你可以像这样得到宽度/高度:

  DrawFrame frame = new DrawFrame();
int theWidth = frame.getWidth();
int theHeight = frame.getHeight();

我强烈建议你使用后一种方法。

关于java - 从另一个类访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1022880/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com