我试图将Person类的toString()方法添加到GUI:
public GUI_Persons() {
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTextPane textPane = new JTextPane();
textPane.setBounds(0, 38, 434, 223);
for(Person person : Access.getAllPersons()) {
textPane.setText(textPane.getText() + person.toString() + "\n");
}
contentPane.add(textPane);
JLabel lblAllPersons = new JLabel("All persons information");
lblAllPersons.setBounds(10, 11, 188, 16);
contentPane.add(lblAllPersons);
}
不幸的是,只显示了一个空白文本字段。有人知道为什么文本不会被设置为JTextPane组件?我还使用了一个方法运行,因为如果用户点击"查看人员"另一帧中的按钮:
public static void run() {
try {
GUI_Persons frame = new GUI_Persons();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
这是toString()方法:
public String toString()
{
return "ID: " + id + ", Type: " + this.getClass().getSimpleName() +", Name: " + name + ", Forename: " + forename + ", Adress: " + adr.toString();
}
提前感谢所有信息。
答案 0 :(得分:0)
嗨svb你的代码工作正常,如果我改变使用Person的循环,我不会有的类,我把它放在真正的类中:
public class GUI_Persons extends JFrame {
public GUI_Persons() {
setBounds(100, 100, 450, 300);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTextPane textPane = new JTextPane();
textPane.setBounds(0, 38, 434, 223);
for (int i = 0; i < 100; i++) {
textPane.setText(textPane.getText() + personToString(i) + "\n");
}
contentPane.add(textPane);
JLabel lblAllPersons = new JLabel("All persons information");
lblAllPersons.setBounds(10, 11, 188, 16);
contentPane.add(lblAllPersons);
}
public static String personToString(int i) {
int id = i;
String name = "name" + i;
String forename = "forename" + i;
String adr = "AAA";
return "ID: " + id + ", Type: " + ", Name: " + name + ", Forename: "
+ forename + ", Adress: " + adr.toString();
}
public static void main(String[] args) {
try {
GUI_Persons frame = new GUI_Persons();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
你可以自己尝试,所以不是摆动问题...... 非常奇怪...只需验证代码的其他部分,或者请提供可执行的内容。