[英]How to access the variables of a function of a class from another class in Java
[英]Access variables from another class in java
我正在嘗試在Java中編寫一個非常簡單的項目。 我正在嘗試創建2個類,其中主要的一個在類2中執行一個方法來創建一個新的JFrame對象。 然后,主類排除了類2中的方法以設置2變量的值。 然后,應該在JFrame面板上以設置的x和y值打印一個字符串。 但是,好像xPos和yPos未被更改,並且字符串以0,0打印。
這是代碼:
import java.awt.*;
import javax.swing.*;
public class Test {
public static void main(String[] args){
Class2 obj = new Class2();
obj.createJFrame();
obj.setVal(100, 200);
}
}
class Class2 extends JPanel{
private int xPos, yPos;
public void createJFrame(){
JFrame window = new JFrame();
Class2 obj2 = new Class2();
window.setVisible(true);
window.setSize(300, 300);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = window.getContentPane();
c.add(obj2);
}
public void setVal(int x, int y){
xPos = x;
yPos = y;
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString("This string should be at 100, 200", xPos, yPos);
}
}
附帶說明一下,我認為我的標題不正確,因此如果有人可以通過編輯標題來幫助我,那將是很棒的。 很抱歉,標題與問題不符,但是我是Java新手。 另外,該程序正在對一個更復雜的程序進行建模,因此,如果此方法似乎不能有效地實現間接,那是因為更復雜的程序將使用這樣的結構。 先感謝您。
class Class2 extends JPanel{
private int xPos, yPos;
public void createJFrame(){
JFrame window = new JFrame();
// Class2 obj2 = new Class2();
window.setVisible(true);
window.setSize(300, 300);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = window.getContentPane();
c.add(this); // now the setValue will update the object
}
...
您沒有更新添加到JFrame中的對象。 順便說一句,我將在靜態方法或其他類中創建JFrame並將Class2作為參數。 就像是:
class Class2 extends JPanel{
private int xPos, yPos;
public static void createJFrame(Class2 obj){
JFrame window = new JFrame();
window.setVisible(true);
window.setSize(300, 300);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = window.getContentPane();
c.add(obj);
}
public void setVal(int x, int y){
xPos = x;
yPos = y;
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString("This string should be at 100, 200", xPos, yPos);
}
}
public class Test {
public static void main(String[] args){
Class2 obj = new Class2();
obj.setVal(100, 200);
Class2.createJFrame(obj);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.