[英]How to update Jlabel Text in Swing
我有一個簡單的GUI文件,它在這里: 每次選擇新文件時,我都想更新Label文本。但是,當我選擇任何文件時,它在現有的Jlabel文本上重疊,因此,請幫助我更新我的JLabel文本。
這是我的代碼:
protected static void excelButtonAction(){
excelReturnVal = fc.showOpenDialog(excelButton);
if(excelReturnVal==JFileChooser.APPROVE_OPTION){
FileValidation.excelFileValidation(fc);
System.out.println(FileValidation.getName() );
if(status==JFileChooser.CANCEL_OPTION){
}else{
fileName=FileValidation.getName();
FileValidation.updatemylabel(fileName);
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
excelFileName.setBounds(140, 67, 350, 30);
excelFileName.setFont(new Font("Myriad Pro",Font.PLAIN,10));
panel.add(excelFileName);
panel.revalidate();
panel.repaint();
}
} else{
System.out.println("Open command cancelled by user." + newline);
}
}
public static void updatemylabel(String exfileName){
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
JFileChooser chooser = new JFileChooser();
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())){
JFileChooser chooser = (JFileChooser) evt.getSource();
File oldFile = (File) evt.getOldValue();
File newFile = (File) evt.getNewValue();
File curFile = chooser.getSelectedFile();
}else if(JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(evt.getPropertyName())){
JFileChooser chooser = (JFileChooser)evt.getSource();
File[] oldFiles = (File[])evt.getOldValue();
File[] newFiles = (File[])evt.getNewValue();
File[] files = chooser.getSelectedFiles();
}
}
});
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
excelFileName.setBounds(140, 67, 350, 30);
excelFileName.setFont(new Font("Myriad Pro",Font.PLAIN,10));
panel.add(excelFileName);
panel.revalidate();
panel.repaint();
existingText=exfileName;
}
讓我知道是否需要進一步的信息來解決我的問題。 預先感謝您的合作。
您的代碼每次都會創建一個新的JLabel
實例。 您需要創建一次實例,將其存儲在類的字段中,並在需要更新時調用setText()
。
您可以查看以下內容,以更好地理解java中的標簽:
的setText
公共無效setText(字符串文本)
定義此組件將顯示的單行文本。 如果text的值為null或空字符串,則不顯示任何內容。 此屬性的默認值為null。
這是JavaBeans的綁定屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.