我正在尝试在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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句