我正在尝试用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);
}
}
关于java - 从java中的另一个类访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40053879/