gpt4 book ai didi

java - 为什么JProgressBar值不刷新?

转载 作者:行者123 更新时间:2023-12-01 13:54:40 26 4
gpt4 key购买 nike

我想做的是,当我单击一个按钮时,我从 USB 等可移植驱动器复制一些文件,并将这些文件复制到我的本地驱动器,然后我读取之前复制的所有 csv 文件,并输入它的值在数组列表中并将其注入(inject)数据库,然后我可以删除这些文件,并且我想根据进程完成情况显示进程进度条。这就是我所做的:

           void main()
{
JButton btnTransfer = new JButton("Transfer");
Image transferIMG = ImageIO.read(new File("C:\\Users\\User\\Desktop\\images\\transfer.png"));
btnTransfer.setIcon(new ImageIcon(transferIMG));
btnTransfer.setPreferredSize(new Dimension(110, 90));
btnTransfer.setOpaque(false);
btnTransfer.setContentAreaFilled(false);
btnTransfer.setBorderPainted(false);
btnTransfer.setVerticalTextPosition(SwingConstants.BOTTOM);
btnTransfer.setHorizontalTextPosition(SwingConstants.CENTER);
btnTransfer.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
File csvpath = new File(fileList1.getSelectedValue() + "\\salestablet\\report\\csv");
File htmlpath = new File(fileList1.getSelectedValue() + "\\salestablet\\report\\html");
String removepath = fileList1.getSelectedValue() + "\\salestablet\\report";

if(csvpath.listFiles().length > 0 && htmlpath.listFiles().length > 0)
{
File[] csvarr = csvpath.listFiles();
File[] htmlarr = htmlpath.listFiles();

try
{
copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath);
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});

JPanel ButtonCont = new JPanel(new GridLayout(4, 1, 5, 0));
ButtonCont.setBackground(Color.LIGHT_GRAY);

ButtonCont.add(btnTransfer);

gui.add(ButtonCont , BorderLayout.EAST);

frame.setContentPane(gui);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setMinimumSize(new Dimension(900, 100));
frame.pack();
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

private static void copyFileUsingStream(File[] csvsources, File[] htmlsources, String dest, String removepath) throws IOException
{
int count = 0;
int MaxCount = countprocess(csvsources, htmlsources);

progressBar = new JProgressBar(0, MaxCount);
progressBar.setStringPainted(true);

InputStream is = null;
OutputStream os = null;

String csvfolderpath = dest + "\\csv";
String htmlfolderpath = dest + "\\html";

if(!(new File(csvfolderpath)).exists())
{
(new File(csvfolderpath)).mkdirs(); //create csv folder;
}

if(!(new File(htmlfolderpath)).exists())
{
(new File(htmlfolderpath)).mkdirs(); //create csv folder;
}

for(int i= 0; i < csvsources.length; i++) //copy all csv files to csv folder
{
try
{
is = new FileInputStream(csvsources[i]);
os = new FileOutputStream(csvfolderpath + "\\" + csvsources[i].getName());
byte[] buffer = new byte[1024];
int length;

while ((length = is.read(buffer)) > 0)
{
os.write(buffer, 0, length);
}
}
finally
{
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());

is.close();
os.close();
}
}

for(int i= 0; i < htmlsources.length; i++) //copy all html, images and css to html folder
{
if(htmlsources[i].isFile())
{
try
{
is = new FileInputStream(htmlsources[i]);
os = new FileOutputStream(htmlfolderpath + "\\" + htmlsources[i].getName());
byte[] buffer = new byte[1024];
int length;

while ((length = is.read(buffer)) > 0)
{
os.write(buffer, 0, length);
}
}
finally
{
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());

is.close();
os.close();
}
}
else if(htmlsources[i].isDirectory()) //for subfolder
{
String path = dest + "\\html\\" + htmlsources[i].getName();

if(!new File(path).exists())
{
(new File(path)).mkdirs(); //create subfolder;
}

File[] arr = (new File(htmlsources[i].getAbsolutePath())).listFiles();

for(int j = 0; j < arr.length; j++)
{
if(arr[j].isFile())
{
try
{
is = new FileInputStream(arr[j]);
os = new FileOutputStream(path + "\\" + arr[j].getName());
byte[] buffer = new byte[1000000];
int length;

while ((length = is.read(buffer)) > 0)
{
os.write(buffer, 0, length);
}
}
finally
{
if(htmlsources[i].getName().contains("images"))
{
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}

is.close();
os.close();
}
}
}
}
}

ArrayList<String > DBValues = new ArrayList<String>(); //read all csv files values

File f1 = new File(csvfolderpath);
for(int i = 0; i < f1.listFiles().length; i++)
{
if(f1.listFiles()[i].isFile())
{
FileReader fl = new FileReader(f1.listFiles()[i]);
BufferedReader bfr = new BufferedReader(fl);

for(int j = 0; j < 2; j++)
{
if(j == 1)
{
DBValues.add(bfr.readLine());

count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
else
{
bfr.readLine();
}
}
bfr.close();
}
}

/*for(int x = 0; x < DBValues.size(); x++)
{
//System.out.println(DBValues.get(x));
}*/

//removing csv in local computer
File f2 = new File(csvfolderpath);
File[] removelist = f2.listFiles();
for(int x = 0; x < removelist.length; x++)
{
if(removelist[x].isFile())
{
removelist[x].delete();

count += 1;
progressBar.setValue((count / MaxCount) * 100);
// progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
}

//removing csv in device
File f3 = new File(removepath + "\\csv");
if(f3.isDirectory())
{
removelist = f3.listFiles();

for(int y = 0; y < removelist.length; y++)
{
try
{
if(removelist[y].isFile())
{
//System.out.println(removelist[y].getName());
removelist[y].delete();
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
// progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

//removing html and images in device
File f4 = new File(removepath + "\\html");
if(f4.isDirectory())
{
removelist = f4.listFiles();

for(int z = 0; z < removelist.length; z++)
{
try
{
if(removelist[z].isFile())
{
removelist[z].delete();

count += 1;
progressBar.setValue((count / MaxCount) * 100);
// progressBar.repaint();
// progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
else if(removelist[z].isDirectory())
{
if(removelist[z].getName().contains("images"))
{
File[] subfolder = removelist[z].listFiles();

for (int idx = 0; idx < subfolder.length; idx++)
{
if(subfolder[idx].isFile())
{
subfolder[idx].delete();

count += 1;
progressBar.setValue((count / MaxCount) * 100);
// progressBar.repaint();
// progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
}
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

/* JProgressBar progressBar = new JProgressBar();
progressBar.setValue(25);
progressBar.setStringPainted(true);*/
Border border = BorderFactory.createTitledBorder("Reading...");
progressBar.setBorder(border);


gui.add(progressBar, BorderLayout.SOUTH);
gui.repaint();
gui.revalidate();


// System.out.println(count);
}

private static int countprocess(File[] csv, File[] html_image)
{
int x = 0;
int y = 0;
int z = 0;

for(int i = 0; i < csv.length; i++)
{
if(csv[i].isFile())
{
x += 1;
}
} //get total count of csv files throught loop

for(int i = 0; i < html_image.length; i++)
{
if(html_image[i].isFile())
{
y += 1;
}
else if(html_image[i].isDirectory())
{
if(html_image[i].getName().contains("images"))
{
File[] flist = html_image[i].listFiles();

for(int j = 0; j < flist.length; j++)
{
z += 1;
}
}
} //get total count of html and images files throught loop
}

return ((4*x) + (2*y) + (2*z));
}

所以我尝试通过像这样设置它的值来刷新我的进度条值

progressBar.setValue((count/MaxCount) * 100);

但不知怎的,我无法让它工作,我的进度条没有显示它的进度,如 1% 2% 3%.. 10% 等等.. 相反,它只在进程完成时显示 100%..我想念这里什么?注意:我也尝试过以这种方式设置进度条值 progressBar.setValue(count); 仍然没有运气。

最佳答案

检查整个代码需要一段时间。但是,在您的 btnTransfer.addActionListeneractionPerformed 函数中,您尝试复制流,这可能需要一段时间。任何类型的事件监听器都在事件调度线程中执行。请refer to this answer更多细节。

现在作为一个快速解决方案:

  • 将您的 copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath); 函数放入内联线程中:

       new Thread()
    {
    public void run()
    {
    copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath);
    }
    }.start();

    }
  • JProgressBar 的进度更新放入 SwingUtilities.invokeLater 中,并通过转换其中之一来进行 (count/MaxCount) 计算它们为double,如下所示:

    SwingUtilities.invokeLater(new Runnable() {

    @Override
    public void run() {

    count += 1;
    progressBar.setValue((int) (((double)count/ MaxCount) * 100));
    }
    });

as countcopyFileUsingStream 函数的本地函数,请尝试在类上下文中声明它以进行访问和更改。

但是 SwingWorker 更适合此类任务。

教程资源:

  1. Worker Threads and SwingWorker
  2. How to use progress bars with swing worker
  3. ProgressBar Demo with SwingWorker

关于java - 为什么JProgressBar值不刷新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19686789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com