我正在尝试在GUI中的textArea
中显示X.509证书的公钥,而不是使用System.out.println()
。当我尝试使用setText()
在textArea中显示它时,它没有在textArea
中显示它。以下方法readCertificate
提取证书的字段,ActionPerformed(ActionEvent e)
只是激活操作的底部:
public void actionPerformed(ActionEvent e){
File f = new File("/Users/AhmadAseeri/Desktop/cer.cer");
Read r = new Read();
r.readCertificate(f);
}
public void readCertificate(File f) throws Exception {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
while (in.available() > 0) {
Certificate cert = cf.generateCertificate(in);
String c=String.valueOf(cert.getPublicKey());
JTextArea textArea= new JTextArea();
textArea.setText(c);
}
in.close();
}
答案 0 :(得分:1)
答案 1 :(得分:1)
如前所述:
while
循环内创建了此文本区域,这是错误的。初始化GUI时,必须创建文本区域并将其添加到容器中。输入 - 输出操作是耗时的任务,可能会阻止Event Dispatch Thread(a.k.a.EDT)导致GUI无响应。要避免此问题,请考虑使用SwingWorker在后台线程中执行IO操作并更新EDT中的Swing组件。在Concurrency in Swing trail
中查看有关此问题的更多信息public void readCertificate(final File f) {
SwingWorker<Void, String> worker = new SwingWorker<Void, String>() {
@Override
protected Void doInBackground() throws Exception {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
while (in.available() > 0) {
Certificate cert = cf.generateCertificate(in);
String c = String.valueOf(cert.getPublicKey());
publish(c);
}
in.close();
return null;
}
@Override
protected void process(List<String> chunks) {
for(String key : chunks) {
textArea.append(key + System.lineSeparator());
}
}
};
worker.execute();
}
答案 2 :(得分:0)
您的问题是,您正在方法textArea
内的while
循环内创建readCertificate(File f)
:
public void readCertificate(File f) throws Exception {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
while (in.available() > 0) {
Certificate cert = cf.generateCertificate(in);
String c=String.valueOf(cert.getPublicKey());
JTextArea textArea= new JTextArea();//????????????????????????????????
textArea.setText(c);
}
in.close();
}
您必须在框架/面板上或在需要时创建它,但不能在那里创建。