Java 从另一个类访问变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1022880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:21:43  来源:igfitidea点击:

accessing a variable from another class

javavariables

提问by

Very simple question but I can't do it. I have 3 classes:

很简单的问题,但我做不到。我有3个班级:

DrawCircleclass

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

DrawFrameclass

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

CircMainclass

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

One class creates a frame, the other draws a circle and fills it with smaller circles. In DrawFrameI set width and height. In DrawCircleI need to access the width and height of DrawFrame. How do I do this?

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

I've tried making an object and tried using .getWidthand .getHeightbut can't get it to work. I need specific code here because I've tried a lot of things but can't get it to work. Am I declaring width and height wrong in DrawFrame? Am creating the object the wrong way in DrawCircle?

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

Also, the variables i use in DrawCircle, should I have them in the constructor or not?

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

回答by Peter

You could make the variables public fields:

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

  public int width;
  public int height;

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

You could then access the variables like so:

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

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

A better solution, however, would be to make the variables private fields add two accessor methods to your class, keeping the data in the DrawFrame class encapsulated:

然而,更好的解决方案是让变量私有字段向您的类添加两个访问器方法,将 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;
  }

Then you can get the width/height like so:

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

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

I strongly suggest you use the latter method.

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

回答by Tom

I've tried making an object and tried using .getWidth and .getHeight but can't get it to work.

我尝试制作一个对象并尝试使用 .getWidth 和 .getHeight 但无法让它工作。

That′s because you are not setting the width and height fields in JFrame, but you are setting them on local variables. Fields HEIGHT and WIDTH are inhereted from ImageObserver

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

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

See http://java.sun.com/javase/6/docs/api/javax/swing/JFrame.html

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

If width and height represent state of the frame, then you could refactorize them to fields, and write getters for them.

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

Then, you could create a Constructor that receives both values as parameters

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

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
}

If widht and height are going to be constant (after created) then you should use the finalmodifier. This way, once they are assigned a value, they can′t be modified.

如果宽度和高度将保持不变(创建后),那么您应该使用final修饰符。这样,一旦它们被赋值,它们就不能被修改。

Also, the variables i use in DrawCircle, should I have them in the constructor or not?

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

The way it is writen now, will only allow you to create one type of circle. If you wan′t to create different circles, you should overload the constructor with one with arguments).

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

For example, if you want to change the attributes xPoint and yPoint, you could have a constructor

例如,如果你想改变属性 xPoint 和 yPoint,你可以有一个构造函数

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

EDIT:

编辑:

Where does _width and _height come from?

Those are arguments to constructors. You set values on them when you call the Constructor method.

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

In DrawFrame I set width and height. In DrawCircle I need to access the width and height of DrawFrame. How do I do this?

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

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

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

   // other stuff

}

Now when the DrawCircle constructor executes, it will receive the values you used in DrawFrame as _width and _height respectively.

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

EDIT:

编辑:

Try doing

尝试做

 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

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

回答by akf

if what you need is the width and height of the frame in the circle, why not pass the DrawFrame width and height into the DrawCircle constructor:

如果您需要的是圆圈中框架的宽度和高度,为什么不将 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;
}

you could also add a couple new methods to DrawCircle:

您还可以向 DrawCircle 添加几个新方法:

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

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

or even:

甚至:

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

if you go down this route, you will need to update DrawFrame to make a local var of the DrawCircle on which to call these methods.

如果您沿着这条路线走下去,您将需要更新 DrawFrame 以创建 DrawCircle 的本地变量,以便在其上调用这些方法。

edit:

编辑:

when changing the DrawCircle constructor as described at the top of my post, dont forget to add the width and height to the call to the constructor in DrawFrame:

当按照我帖子顶部的描述更改 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));
 }
}

回答by Lloyd McFarlin

I hope I'm understanding the problem correctly, but it looks like you don't have a reference back to your DrawFrame object from DrawCircle.

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

Try this:

尝试这个:

Change your constructor signature for DrawCircle to take in a DrawFrame object. Within the constructor, set the class variable "d" to the DrawFrame object you just took in. Now add the getWidth/getHeight methods to DrawFrame as mentioned in previous answers. See if that allows you to get what you're looking for.

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

Your DrawCircle constructor should be changed to something like:

您的 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;
}

The last line of code in DrawFrame should look something like:

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

contentPane.add(new DrawCircle(this));

Then, try using d.getheight(), d.getWidth() and so on within DrawCircle. This assumes you still have those methods available on DrawFrame to access them, of course.

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

回答by LifesAway

I had the same problem. In order to modify variables from different classes, I made them extend the class they were to modify. I also made the super class's variables static so they can be changed by anything that inherits them. I also made them protected for more flexibility.

我有同样的问题。为了修改来自不同类的变量,我让它们扩展了要修改的类。我还将超类的变量设为静态,以便任何继承它们的东西都可以更改它们。我还保护它们以获得更大的灵活性。

Source:Bad experiences. Good lessons.

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

回答by Marwan Salim

Filename=url.java

文件名=url.java

public class url {

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

}

if u want to call the variable just use this:

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

url.BASEURL+ "your code here";

url.BASEURL+ "你的代码在这里";

回答by niks

Java inbuilt libraries support only AIFC, AIFF, AU, SND and WAVE formats. Here I only discussed playing an audio file using Clip only and see the various methods of a clip.

Java 内置库仅支持 AIFC、AIFF、AU、SND 和 WAVE 格式。这里我只讨论了仅使用 Clip 播放音频文件,并查看了 Clip 的各种方法。

  1. Create a main class PlayAudio.java.
  2. Create helper class Audio.java.
  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);

   }

}