簡體   English   中英

從另一個類訪問變量

[英]accessing a variable from another class

很簡單的問題,但我做不到。 我有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 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();

我強烈建議您使用后一種方法。

我有同樣的問題。 為了修改來自不同類的變量,我讓它們擴展了要修改的類。 我還將超類的變量設為靜態,以便任何繼承它們的東西都可以更改它們。 我還保護它們以獲得更大的靈活性。

來源:糟糕的經歷。 良好的教訓。

我嘗試制作一個對象並嘗試使用 .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 中使用的變量,我應該在構造函數中使用它們嗎?

現在寫的方式,只允許你創建一種類型的 circle 如果你不想創建不同的圓圈,你應該用一個帶參數的構造函數重載)。

例如,如果你想改變屬性 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

如果您需要的是圓圈中框架的寬度和高度,為什么不將 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));
 }
}

我希望我能正確理解這個問題,但看起來你沒有從 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 上使用這些方法來訪問它們。

文件名=url.java

public class url {

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

}

如果你想調用變量,只需使用這個:

url.BASEURL + "你的代碼在這里";

Java 內置庫僅支持 AIFC、AIFF、AU、SND 和 WAVE 格式。 這里我只討論了僅使用 Clip 播放音頻文件,並查看了 Clip 的各種方法。

  1. 創建一個主類PlayAudio.java
  2. 創建輔助類Audio.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();
   }
}

音頻文件

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

   }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM