共計(jì) 1052 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
要將一個(gè)對(duì)象添加到文本域中,需要使用文本域的 append
方法。如果要在文本域中顯示對(duì)象的內(nèi)容,可以將對(duì)象轉(zhuǎn)換為字符串形式,然后將該字符串追加到文本域中。
以下是一個(gè)示例代碼,演示了如何將一個(gè)自定義的對(duì)象添加到文本域中:
import javax.swing.*;
import java.awt.*;
public class MainFrame extends JFrame {public MainFrame() {JTextArea textArea = new JTextArea();
JButton button = new JButton("Add Object");
button.addActionListener(e -> {
// 創(chuàng)建一個(gè)自定義對(duì)象
Person person = new Person("John", 25);
// 將對(duì)象轉(zhuǎn)換為字符串形式
String objectString = person.toString();
// 將字符串追加到文本域中
textArea.append(objectString + "\n");
});
JPanel panel = new JPanel();
panel.add(button);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER);
getContentPane().add(panel, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setVisible(true);
}
public static void main(String[] args) {SwingUtilities.invokeLater(() -> new MainFrame());
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {return "Name:" + name + ", Age:" + age;}
}
運(yùn)行上述代碼,點(diǎn)擊 ”Add Object” 按鈕后,會(huì)將一個(gè)自定義的 Person 對(duì)象的字符串表示追加到文本域中。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完