从另一个类访问变量

时间:2009-06-21 00:37:24

标签: java variables

非常简单的问题,但我不能这样做。我有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中使用的变量,是否应该在构造函数中使用它们?

7 个答案:

答案 0 :(得分:42)

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

  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;

然而,更好的解决方案是使变量私有字段为您的类添加两个访问器方法,保持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();

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

答案 1 :(得分:4)

我遇到了同样的问题。为了修改来自不同类的变量,我让它们扩展了它们要修改的类。我还将超类的变量设置为静态,以便可以通过继承它们的任何内容来更改它们。我也让它们受到保护以获得更大的灵活性。

来源:糟糕的经历。很好的教训。

答案 2 :(得分:1)

  

我尝试制作一个物品并尝试过   使用.getWidth和.getHeight但是   无法让它发挥作用。

这是因为您没有在JFrame中设置宽度和高度字段,而是在局部变量上设置它们。字段HEIGHT和WIDTH来自ImageObserver

Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

请参阅 http://java.sun.com/javase/6/docs/api/javax/swing/JFrame.html

如果宽度和高度代表帧的状态,那么你可以将它们重构为字段,并为它们编写getter。

然后,您可以创建一个构造函数,将两个值作为参数

接收
public class DrawFrame extends JFrame {
 private int width;
 private int height;

 DrawFrame(int _width, int _height){

   this.width = _width;
   this.height = _height;

   //other stuff here
}
 public int getWidth(){}
 public int getHeight(){}

 //other methods
}

如果widht和height将保持不变(创建后),则应使用 final 修饰符。这样,一旦为它们分配了值,就无法修改它们。

  

此外,我使用的变量   DrawCircle,我应该把它们放进去   构造函数与否?

现在编写的方式只允许您创建一种类型的圆。如果你不想创建不同的圆圈,你应该用一个带参数的构造函数重载。)

例如,如果要更改属性xPoint和yPoint,则可以使用构造函数

public DrawCircle(int _xpoint, int _ypoint){
  //build circle here.
 }

编辑:

Where does _width and _height come from?

这些是构造函数的参数。在调用Constructor方法时,可以在它们上设置值。

  

在DrawFrame中,我设置宽度和高度。   在DrawCircle中我需要访问   DrawFrame的宽度和高度。怎么做   我这样做了?

DrawFrame(){
   int width = 400;
   int height =400;

   /*
   * call DrawCircle constructor
   */
   content.pane(new DrawCircle(width,height));

   // other stuff

}

现在,当DrawCircle构造函数执行时,它将分别接收您在DrawFrame中使用的值_width和_height。

编辑:

尝试

 DrawFrame frame = new DrawFrame();//constructor contains code on previous edit.
 frame.setPreferredSize(new Dimension(400,400));

http://java.sun.com/docs/books/tutorial/uiswing/components/frame.html

答案 3 :(得分:0)

如果你需要的是圆圈中框架的宽度和高度,为什么不将DrawFrame的宽度和高度传递给DrawCircle构造函数:

public DrawCircle(int w, int h){
    this.w = w;
    this.h = h;
    diBig = 300;
    diSmall = 10;
    maxRad = (diBig/2) - diSmall;
    xSq = 50;
    ySq = 50;
    xPoint = 200;
    yPoint = 200;
}

您还可以为DrawCircle添加一些新方法:

public void setWidth(int w) 
   this.w = w;

public void setHeight(int h)
   this.h = h; 

甚至:

public void setDimension(Dimension d) {
   w=d.width;
   h=d.height;
}

如果你走这条路线,你需要更新DrawFrame来制作一个调用这些方法的DrawCircle的局部变量。

修改

当我按照帖子顶部的描述更改DrawCircle构造函数时,不要忘记在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();
    //pass in the width and height to the DrawCircle contstructor
    contentPane.add(new DrawCircle(width, height));
 }
}

答案 4 :(得分:0)

我希望我能正确理解这个问题,但看起来你没有从DrawCircle那里回到你的DrawFrame对象。

试试这个:

更改DrawCircle的构造函数签名以获取DrawFrame对象。在构造函数中,将类变量“d”设置为刚刚接受的DrawFrame对象。现在将getWidth / getHeight方法添加到DrawFrame中,如前面的答案中所述。看看是否可以让你得到你想要的东西。

你的DrawCircle构造函数应改为:

public DrawCircle(DrawFrame frame)
{
    d = frame;
    w = 400;
    h = 400;
    diBig = 300;
    diSmall = 10;
    maxRad = (diBig/2) - diSmall;
    xSq = 50;
    ySq = 50;
    xPoint = 200;
    yPoint = 200;
}

DrawFrame中的最后一行代码应该类似于:

contentPane.add(new DrawCircle(this));

然后,尝试在DrawCircle中使用d.getheight(),d.getWidth()等。这假设您仍然可以在DrawFrame上使用这些方法来访问它们。

答案 5 :(得分:0)

文件名= url.java

public class url {

    public static final String BASEURL = "http://192.168.1.122/";

}

如果你想调用变量,只需使用它:

url.BASEURL +“您的代码在这里”;

答案 6 :(得分:0)

Java内置库仅支持AIFC,AIFF,AU,SND和WAVE格式。 在这里,我仅讨论了仅使用剪辑播放音频文件的情况,并介绍了剪辑的各种方法。

  1. 创建一个主类PlayAudio.java
  2. 创建助手类Audio.java

PlayAudio.java

import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class PlayAudio {
public static void main(String[] args) throws 
UnsupportedAudioFileException, IOException, 
LineUnavailableException {

    PlayMp3 playMp3;
    playMp3=new PlayMp3();


    Scanner sc = new Scanner(System.in);

    while (true) {
        System.out.println("Enter Choice :-");
        System.out.println("1. Play");
        System.out.println("2. pause");
        System.out.println("3. resume");
        System.out.println("4. restart");
        System.out.println("5. stop");

        System.out.println(PlayMp3.status);
        System.out.println(":::- ");
        int c = sc.nextInt();

        if (c ==5){

            playMp3.stop();
            break;
        }

        switch (c) {
            case 1:
                playMp3.play();
                break;
            case 2:
                playMp3.pause();
                break;
            case 3:
                playMp3.resume();
                break;
            case 4:
                playMp3.restart();
                break;
            case 5:
                playMp3.stop();
            default:
                System.out.println("Please Enter Valid Option :-");

        }
    }
    sc.close();
   }
}

Audio.java

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

public class Audio {

private String filePath="mp.snd";
public static String status="paused";
private Long currentFrame=0L;
private Clip clip;

private AudioInputStream audioInputStream;

public Audio() throws UnsupportedAudioFileException, IOException, LineUnavailableException {

    audioInputStream = AudioSystem.getAudioInputStream(new File(filePath));

    clip = AudioSystem.getClip();

    clip.open(audioInputStream);

}


public void play(){
    clip.start();
    status = "playing";
}

public void pause(){

    if (status.equals("paused")) {
        System.out.println("audio is already paused");
        return;
    }
    currentFrame = clip.getMicrosecondPosition();
    clip.stop();
    status = "paused";
}
public void resume() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
    if (status.equals("play"))
    {
        System.out.println("Audio is already being playing");
        return;
    }
    clip.close();

    //starts again and goes to currentFrame
    resetAudioStream();
    clip.setMicrosecondPosition(currentFrame);
    play();
    status="playing";

}

public void restart() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
    clip.stop();
    clip.close();
    resetAudioStream();
    currentFrame = 0L;
    clip.setMicrosecondPosition(0);
    play();
    status="Playing from start";
}

public void stop(){

    currentFrame = 0L;
    clip.stop();
    clip.close();
    status="stopped";
}

private void resetAudioStream() throws IOException, UnsupportedAudioFileException, LineUnavailableException {

    audioInputStream = AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile());
    clip.open(audioInputStream);

   }

}