【问题标题】:accessing a variable from another class从另一个类访问变量
【发布时间】:2009-06-21 00:37:24
【问题描述】:

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

【问题讨论】:

  • 你尝试过制作什么类的对象?

标签: java variables


【解决方案1】:

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

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

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

【讨论】:

  • 我支持后一种方法的强烈建议(我想和许多其他方法一样。请参阅:stackoverflow.com/questions/393001/…
  • 您好,感谢您的帮助。我之前尝试过这样的事情。我遵循了您的代码,但仍然无法正常工作。一定是其他地方有问题。你有什么建议吗。 OP中的代码有效。我的主类看起来像这样: import java.awt.*;导入 java.awt.event.*;导入 javax.swing.*;公共类 CircMain { public static void main(String[] args) { JFrame frame = new DrawFrame();框架.show();这是导致问题的原因吗?
【解决方案2】:

我遇到了同样的问题。为了修改来自不同类的变量,我让它们扩展了它们要修改的类。我还将超类的变量设为静态,因此它们可以被继承它们的任何东西更改。我还对它们进行了保护以提高灵活性。

来源:糟糕的经历。很好的课程。

【讨论】:

    【解决方案3】:

    我尝试过制作一个对象并尝试过 使用 .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
    }
    

    如果宽度和高度将保持不变(创建后),那么您应该使用 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

    【讨论】:

    • 感谢您的帮助,并为没有得到它而道歉。我无法让它工作。不幸的是,我并没有比 5 小时前更好。 _width 和 _height 从何而来?我有很多不同的做事方式,但没有一种具体的做事方式。
    • 但是是什么将它们传递给构造函数?我从我的主要假设: public static void main(String[] args) { JFrame frame = new DrawFrame(400,400);框架.show();我试过这个,它没有用。基本上我今天早上 9 点还在原处。我怀疑您告诉我的内容不适用于我拥有的其他代码。感谢您的帮助,我将继续学习 java 直到改天。
    • 好的。现在看我的编辑。也许你应该尝试一些更简单的东西。我不认为这是学习 java 或 swing 的方式。
    • 我完全糊涂了。太多的部分答案。我对 java 太陌生了,不会在所有建议中感到困惑。我花了 8 个小时试图传递/访问一个变量。有时您只需要查看代码即可获得它。我怀疑我曾多次接近。谢谢你的帮助,但你完全把我弄糊涂了。
    【解决方案4】:

    我希望我正确理解了这个问题,但您似乎没有从 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 上使用这些方法来访问它们。

    【讨论】:

    • 嗨,试过了。无法让它工作。我尝试了很多不同的东西,错误可能来自其他地方。我想你理解我的问题,但让我澄清一下:我在 DrawFrame 中设置了宽度和高度 在 DrawCircle 中我需要能够访问宽度和高度的值。在我上面的代码(有效)中,我在构造函数中手动重置,而不是从 DrawFrame 中获取它。我只需要设置一次宽度和高度。
    • 我明白了,我完全复制了 DrawCircle 的构造函数,并添加了参数和第一行。根据您的评论,似乎还需要添加:“w = d.getWidth(); h = d.getHeight();”代替“w = 400; h = 400;”
    【解决方案5】:

    如果你需要的是圆中框架的宽度和高度,为什么不将 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 的本地 var 以调用这些方法。

    编辑:

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

    【讨论】:

    • 我收到错误提示“构造函数 DrawCircle 未定义”
    • johnrambo,您的编译器可能在抱怨,因为您将参数更改为构造函数,但您没有更改仍然引用无参数构造函数的 DrawFrame 中的调用。请看我的编辑。
    【解决方案6】:

    文件名=url.java

    public class url {
    
        public static final String BASEURL = "http://192.168.1.122/";
    
    }
    

    如果你想调用变量就用这个:

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

    【讨论】:

      【解决方案7】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 2020-11-24
        • 2015-01-21
        • 1970-01-01
        • 2015-02-28
        相关资源
        最近更新 更多