大家。我正在编写使用jprogressbar的程序。 我不需要知道工作完成的确切百分比,只是想让用户知道程序在计算时是否正常工作。
我想要实现的是,只要用户单击名为" Analyze"的按钮,jprogressbar就会以不确定的模式运行,该模式只是来回移动。我编写了程序,因为jprogressbar在oracle的例子中有解释,但它没有运行。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFileChooser;
@SuppressWarnings( "serial" )
public class FileDragDemo
extends JPanel
{
private JList list = new JList();
private JButton btnCompare, btnAnalyze, btnRefresh;
private JTextField textResultField;
final JFileChooser fc = new JFileChooser();
File settingFile = null;
SettingReader readSetting = null;
public Calculation calculationData = null;
private JProgressBar progressBar;
private Task task;
class Task extends SwingWorker<Void, Void> {
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
Random random = new Random();
int progress = 0;
//Initialize progress property.
setProgress(0);
while (progress < 100) {
//Sleep for up to one second.
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException ignore) {}
//Make random progress.
progress += random.nextInt(10);
setProgress(Math.min(progress, 100));
}
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
setCursor(null); //turn off the wait cursor
}
}
public FileDragDemo()
{
setPreferredSize(new Dimension(410, 165));
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
add(progressBar);
try
{
getFile();
String fileExtension = getFileExtension( settingFile );
if ( fileExtension.equals( "ini" ) )
{
readSetting = new SettingReader(settingFile);
}
while (fileExtension.equals( "ini" ) == false){
JOptionPane.showMessageDialog( null, "Choose .ini file for configuration" );
getFile();
fileExtension = getFileExtension( settingFile );
}
}
catch ( IOException e )
{
e.printStackTrace();
}
list.setDragEnabled( true );
list.setTransferHandler( new FileListTransferHandler( list ) );
JScrollPane scrollPane = new JScrollPane( list );
btnCompare = new JButton( "Compare" );
btnCompare.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent arg0 )
{
progressBar.setIndeterminate(true);
try
{
File file1 = (File) list.getModel().getElementAt( 0 );
File file2 = (File) list.getModel().getElementAt( 1 );
System.out.println( file1.getPath() );
System.out.println( file2.getPath() );
try
{
CompareTwoValues twoValuesToCompare = new CompareTwoValues( file1.getPath(), file2.getPath() );
if ( twoValuesToCompare.result() == true )
{
textResultField.setBackground( Color.green );
textResultField.setText( twoValuesToCompare.toString() );
}
if ( twoValuesToCompare.result() == false )
{
textResultField.setBackground( Color.RED );
textResultField.setText( twoValuesToCompare.toString() );
}
}
catch ( IOException e )
{
JOptionPane.showMessageDialog( null, "File(s) cannot be analyzed or compared" );
e.printStackTrace();
}
}
catch ( java.lang.IndexOutOfBoundsException e )
{
JOptionPane.showMessageDialog( null, "Please select 2 files to compare" );
return;
}
catch ( java.lang.NumberFormatException e)
{
JOptionPane.showMessageDialog( null, "Wrong Input, choose right file to Compare" );
DefaultListModel listModel = (DefaultListModel) list.getModel();
listModel.removeAllElements();
return;
}
progressBar.setIndeterminate(false);
progressBar.setValue(100);
}
} );
btnAnalyze = new JButton( "Analyze" );
btnAnalyze.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent arg0 )
{
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
try
{
TrackReader BinaryReader = null;
File importingFile = (File) list.getModel().getElementAt( 0 );
String fileExtension = getFileExtension( importingFile );
if ( fileExtension.equals( "txt" ) )
{
try
{
BinaryReader = new TextTrackReader( importingFile );
calculationData = new Calculation(BinaryReader, readSetting, progressBar);
}
catch ( IOException e1 )
{
JOptionPane.showMessageDialog( null, "Wrong Input, choose right file to Analyze" );
e1.printStackTrace();
return;
}
}
else
{
if ( fileExtension.equals( "tracks" ) ){
try
{
String BinaryReaderPath1 = importingFile.getAbsolutePath();
BinaryReader = new BinaryTrackReader( BinaryReaderPath1 );
calculationData = new Calculation(BinaryReader, readSetting, progressBar);
}
catch ( IOException | java.lang.NumberFormatException e)
{
JOptionPane.showMessageDialog( null, "Wrong Input, choose right file to Analyze" );
e.printStackTrace();
return;
}
}
else
{
JOptionPane.showMessageDialog( null, "Wrong Input, choose right file to Analyze" );
return;
}
}
progressBar.setIndeterminate(false);
progressBar.setValue(100);
JFrame frame = new JFrame( "Result" );
frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
frame.getContentPane().add( new ResultFrame( calculationData ) );
frame.pack();
frame.setVisible( true );
}
catch ( java.lang.IndexOutOfBoundsException e )
{
JOptionPane.showMessageDialog( null, "File cannot be analyzed. Please choose a correct .ini file and data file" );
e.printStackTrace();
return;
}
catch ( IOException e )
{
e.printStackTrace();
}
catch ( java.lang.NumberFormatException e)
{
JOptionPane.showMessageDialog( null, "Wrong Input, choose right file to Analyze" );
DefaultListModel listModel = (DefaultListModel) list.getModel();
listModel.removeAllElements();
return;
}
}
} );
btnRefresh = new JButton( "Refresh" );
btnRefresh.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent arg0 )
{
try
{
btnAnalyze.setEnabled(true);
btnCompare.setEnabled(true);
DefaultListModel listModel = (DefaultListModel) list.getModel();
listModel.removeAllElements();
}
catch ( java.lang.ClassCastException e )
{
JOptionPane.showMessageDialog( null, "No list to refresh" );
return;
// e.printStackTrace();
}
}
} );
textResultField = new JTextField();
textResultField.setHorizontalAlignment( SwingConstants.CENTER );
textResultField.setColumns( 10 );
progressBar = new JProgressBar();
// if (listModel.getSize() > 1){
// btnAnalyze.setEnabled( false );
// }
GroupLayout groupLayout = new GroupLayout( this );
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
.addComponent(progressBar, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
.addComponent(textResultField, 0, 0, Short.MAX_VALUE)
.addComponent(btnRefresh, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAnalyze, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnCompare, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(239, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 144, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(progressBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(btnCompare)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnAnalyze)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnRefresh)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(textResultField)))
.addContainerGap(316, Short.MAX_VALUE))
);
setLayout( groupLayout );
}
private static void createAndShowGui()
{
FileDragDemo mainPanel = new FileDragDemo();
JFrame frame = new JFrame( "OSCAR" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.getContentPane().add( mainPanel );
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
frame.setResizable(false);
}
private static String getFileExtension( File file )
{
String fileName = file.getName();
if ( fileName.lastIndexOf( "." ) != -1 && fileName.lastIndexOf( "." ) != 0 )
return fileName.substring( fileName.lastIndexOf( "." ) + 1 );
else
return "";
}
public void getFile()
throws FileNotFoundException, IOException
{
JFileChooser myChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("INI File", "ini");
myChooser.setFileFilter(filter);
int returnVal = myChooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
settingFile = myChooser.getSelectedFile();
}
else {
System.exit(0);
}
}
public static void main( String[] args )
{
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
createAndShowGui();
}
} );
}
class FileListTransferHandler
extends TransferHandler
{
private JList list;
public FileListTransferHandler( JList list )
{
this.list = list;
}
public int getSourceActions( JComponent c )
{
return COPY_OR_MOVE;
}
public boolean canImport( TransferSupport ts )
{
return ts.isDataFlavorSupported( DataFlavor.javaFileListFlavor );
}
public boolean importData( TransferSupport ts )
{
try
{
@SuppressWarnings( "rawtypes" )
List data = (List) ts.getTransferable().getTransferData( DataFlavor.javaFileListFlavor );
if ( data.size() < 1 )
{
return false;
}
DefaultListModel listModel = new DefaultListModel();
for ( Object item : data )
{
File file = (File) item;
listModel.addElement( file );
}
list.setModel( listModel );
if ( list.getModel().getSize() == 2 )
{
btnCompare.setEnabled( true );
btnAnalyze.setEnabled( false );
}
else if ( list.getModel().getSize() == 1 )
{
btnCompare.setEnabled( false );
btnAnalyze.setEnabled( true );
}
else if ( list.getModel().getSize() > 2 )
{
JOptionPane.showMessageDialog( null, "Choose one or two files" );
listModel = (DefaultListModel) list.getModel();
listModel.removeAllElements();
}
return true;
}
catch ( UnsupportedFlavorException e )
{
return false;
}
catch ( IOException e )
{
return false;
}
}
}
}
我做错了什么?对于jprogressbar的不确定模式,我认为我甚至不需要运行该线程。请帮帮我。 提前谢谢。