簡體   English   中英

Java 框架在 while 循環期間無法正確顯示

[英]Java frame not displaying properly during a while loop

這是我在使用 jFrame 時遇到的一個嚴重問題。 我有一個“主框架”,一切都是從那里完成的,但是我有另一個框架,里面有一個 gif 圖像(正在加載,那個圓圈一圈又一圈),用作啟動畫面,上面寫着“正在處理,請稍候” ,但是當我穿過那個框架並且我的 while 循環運行時,框架變為空白,直到循環之后才顯示任何內容。

我假設這是由於 while 循環消耗了計算機資源並“阻止”了任何其他進程的運行。

請建議我應該怎么做。

聲明新框架的代碼是標准的,但我還是會在下面發布。

Processing nc = new Processing();
nc.setVisible(true);

這是我的完整代碼,因此您可以看到我正在嘗試實現的目標:

第 1 幀中的代碼(Excel 提取器):

Processing nc = new Processing();
    nc.setVisible(true);

    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int option = chooser.showOpenDialog(this); // parentComponent must a component like JFrame, JDialog...
    if (option == JFileChooser.APPROVE_OPTION) {
    File selectedFile = chooser.getSelectedFile();
     directory = selectedFile.getAbsolutePath();
     System.out.println(directory);

    }


   //create a input stream for your excel file from which data will be read. 
   DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
   SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
   String curdate = dateFormat.format(new Date());
   Calendar cal = Calendar.getInstance();
   cal.getTime();
   String curtime = sdf.format(cal.getTime());
try{

FileInputStream excelSheetInput = new FileInputStream(path);
//POIFSFileSystem myFileSystem = new POIFSFileSystem(excelSheetInput);
    XSSFWorkbook myWorkBook = new XSSFWorkbook(excelSheetInput);
    //get first work sheet in your excel file.
    Sheet sheet = myWorkBook.getSheetAt(0);
    //we will read data in first rows(0) second column(1)
    Iterator<Row> rowIterator = sheet.iterator();
    Row myRow1 = sheet.getRow(0);
    Cell myCell1 = myRow1.getCell(0);
    String header="";
    Iterator<Cell> cellIterator1 = myRow1.cellIterator();
    int rowCount = 0;

    while(cellIterator1.hasNext()) {

                            Cell cell1 = cellIterator1.next();

                            switch(cell1.getCellType()) {
                                case Cell.CELL_TYPE_BOOLEAN:
                                    header = header + "\""+cell1.getBooleanCellValue()+"\"" + ",";
                                    break;
                                case Cell.CELL_TYPE_NUMERIC:
                                    cell1.setCellType(Cell.CELL_TYPE_STRING);
                                     header = header + "\""+cell1.getStringCellValue()+"\""+",";
                                    //System.out.print(cell.getStringCellValue() + "\t\t");
                                    break;
                                case Cell.CELL_TYPE_STRING:
                                    header = header + "\""+cell1.getStringCellValue()+"\""+",";
                                    //System.out.print(cell.getStringCellValue() + "\t\t");
                                    break;
                            }
    }

    Row myRow = sheet.getRow(1);
    Cell myCell= myRow.getCell(0);
    Iterator<Cell> cellIterator;
    String firstCell = myCell.getStringCellValue();
    int count =1;
    String nextCell;
    String Matter = "Matter Number: "+firstCell;
    String num = firstCell;
    System.out.println(Matter);
    fWriter = new FileWriter(new File(directory, num+"_"+curdate+"_"+curtime+".csv"));
    writer = new BufferedWriter(fWriter);
    writer.write(Matter);
    writer.newLine();
    writer.write(header);
    writer.newLine();
    String temp;
    while(rowIterator.hasNext())
    {


        //temp = "" + rowCount;
        //jLabel5.setText(temp);
        myRow = sheet.getRow(count);
        cellIterator = myRow.cellIterator();
        Cell myCell2 = myRow.getCell(0);
        nextCell= myCell2.getStringCellValue();


        if(nextCell.equals(firstCell))
        {

            while(cellIterator.hasNext()) {

                            Cell cell = cellIterator.next();

                            switch(cell.getCellType()) {
                                case Cell.CELL_TYPE_BOOLEAN:
                                    System.out.print(cell.getBooleanCellValue() + "\t\t");
                                    break;
                                case Cell.CELL_TYPE_NUMERIC:
                                    cell.setCellType(Cell.CELL_TYPE_STRING);

                                     System.out.print(cell.getStringCellValue()+",");

                                    //System.out.print(cell.getStringCellValue() + "\t\t");
                                    writer.write(cell.getStringCellValue()+",");
                                    break;
                                case Cell.CELL_TYPE_STRING:
                                    System.out.print(cell.getStringCellValue()+",");
                                    //System.out.print(cell.getStringCellValue() + "\t\t");
                                    writer.write(cell.getStringCellValue()+",");
                                    break;
                            }
                        }
            System.out.println();
            writer.newLine();
            count++;
            rowCount++;



        }
        else
        {          

            writer.close();
            myRow = sheet.getRow(count);
            myCell2= myRow.getCell(0);
            nextCell=myCell2.getStringCellValue();
            firstCell=nextCell;
            Matter = "Matter Number: "+firstCell;
            num = firstCell;
            System.out.println(Matter);
            fWriter = new FileWriter(new File(directory, num+"_"+curdate+"_"+curtime+".csv"));
            writer = new BufferedWriter(fWriter);
            writer.write(Matter);
            writer.newLine();
            writer.write(header);
            writer.newLine();
        }


    }
}
catch (Exception e)
{
}

  try {
    nc.dispose();
    writer.close();
} catch (IOException ex) {
    Logger.getLogger(FileChooser.class.getName()).log(Level.SEVERE, null, ex);
}
}

第二幀代碼(Processing):

private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    jLabel1.setText("Processing, Please Wait...");

    jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/loading.gif"))); // NOI18N

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jLabel2)
            .addContainerGap())
    );

    pack();
}

在不知道您嘗試做的全部范圍的情況下,您不可能完全得到確切的答案。

從您嘗試在事件調度線程的上下文中運行長時間運行的任務的聲音來看。 該線程負責處理重繪請求等。

阻止此線程可防止 Swing 重新繪制自身。

據我所知,您想使用SwingWorker 這將允許您在后台線程中執行您的工作,同時將更新重新同步回 EDT

更新示例

我知道你說不想“想”使用SwingWorker ,但說實話,它更簡單,更安全......

在此處輸入圖片說明

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class LongRunningTask {

    public static void main(String[] args) {
        new LongRunningTask();
    }

    public LongRunningTask() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                new BackgroundWorker().start();

            }
        });
    }

    public class BackgroundWorker extends SwingWorker<Object, Object> {

        private JFrame frame;

        public BackgroundWorker() {
        }

        // Cause exeute is final :P
        public void start() {
            ImageIcon icon = new ImageIcon(getClass().getResource("/spinner.gif"));
            JLabel label = new JLabel("This might take some time");
            label.setIcon(icon);

            frame = new JFrame("Testing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new GridBagLayout());
            frame.add(label);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);

            execute();
        }

        @Override
        protected Object doInBackground() throws Exception {

            System.out.println("Working hard...");
            Thread.sleep(1000 + (((int)Math.round(Math.random() * 5)) * 1000));
            System.out.println("Or hardly working...");

            return null;

        }

        @Override
        protected void done() {
            frame.dispose();
        }

    }
}

您使用 java.util 包中的 Timer 類並安排 timertask 在一段時間后關閉啟動屏幕,例如 2 分鍾或任務完成。

 final Processing nc = new Processing();
 nc.setVisible(true);
 Timer timer = new Timer():
 TimerTask task = new TimerTask() {
      public void run() { 
          nc.setVisible( false );
          // to do disposing nc
      }
 };
 timer.schedule( task, 1000 * 3 ); // dispose the processing frame after 3 minutes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM