gpt4 book ai didi

java - 是否可以从初始化的类外部更改对象实例?

转载 作者:行者123 更新时间:2023-12-01 22:04:18 24 4
gpt4 key购买 nike

我可能以错误的方式处理这件事。请赐教。提前感谢!!!

void initialize() {
more code...
JEditorPane textPane = new JEditorPane();
textPane.setEditable(false);
textPane.setBackground(Color.LIGHT_GRAY);
textPane.setText(" THE MESSAGE I WANT TO CHANGE FROM OUTSIDE initialize()");
more code....

public static void SomePrintClass(){
JEditorPane textPane = new JEditorPane();
textPane.setText("SOME NEW TEXT ); // I am aware this doesn't work
//but is there a way it can be made to work???
more code.....

最佳答案

我猜您只想更改任何其他类中 JEditorPane 的文本。如果是这样那就很简单了。 使 JEditorPane 静态并使用类的名称调用其 setText() 方法。例如。

头等舱

public class First extends JFrame {

static JEditorPane ep;
First() {
ep = new JEditorPane();
setSize(new Dimension(200, 200));
ep.setText("I expect to receive some text.");
add(ep);
setVisible(true);
}

@Override
public void paintComponents(Graphics g) {
super.paintComponents(g);
}
}

二等。

public class Second extends JFrame {

JButton btn;
JTextField jtf = new JTextField(16);
JEditorPane ep;

Second() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn = new JButton("Send above Text.");
setSize(new Dimension(200, 200));
btn.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
ep = First.ep;
ep.setText(jtf.getText());
ep.setForeground(Color.red);
}

});
this.setLayout(new FlowLayout());
add(jtf);
add(btn);
setVisible(true);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
First so;

@Override
public void run() {
new Second();
so = new First();
}
});
}
}

关于java - 是否可以从初始化的类外部更改对象实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33061019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com