ShortcutPicker类仅使用JFileChooser来选择文件。但是当我将所有路径加载到textFields并尝试调用printData()时,它只会打印出默认值,除了最后一个索引,就会打印出值。
似乎无法找到错误。
希望有人能帮我解决这个问题,谢谢!
class ShortcutPickerPanel extends JPanel
{
private int amountOfShortcuts;
private JTextField[] textFields;
private ShortcutPicker picker = new ShortcutPicker();
public ShortcutPickerPanel( int amountOfShortcuts )
{
this.amountOfShortcuts = amountOfShortcuts;
setLayout( new GridLayout( amountOfShortcuts, 3, 2, 2 ) );
setup();
}
/**
* Method initializes and add component's.
*/
public void setup()
{
this.textFields = new JTextField[ amountOfShortcuts ];
BrowseButtonListener listener = new BrowseButtonListener();
for( int i = 0; i < textFields.length; i++ )
{
textFields[ i ] = new JTextField( "Default", 20 );
BrowseButton button = new BrowseButton( "Browse", i );
JLabel currentLabel = new JLabel( "Shortcut path:" );
button.addActionListener( listener );
add( currentLabel );
add( textFields[ i ] );
add( button);
}
}
/**
* Checks if data in textfields are ok
*/
public boolean dataOk()
{
return true;
}
/**
* Method to print data:
* Lets say i have 2 fields initiated here, only the last field will have a value??
*/
public void printData()
{
System.out.println( "Length: " + textFields.length );
for( int i = 0; i < textFields.length; i++ )
{
System.out.println( textFields[ i ].getText() );
}
}
/**
* Listener for BrowseButton
*/
private class BrowseButtonListener implements ActionListener
{
public void actionPerformed( ActionEvent event )
{
BrowseButton button = ( BrowseButton ) event.getSource();
File selectedFile = picker.chooseFile();
if( selectedFile != null )
{
textFields[ button.getTextFieldIndex() ].setText(
selectedFile.getAbsolutePath() );
}
}
}
/**
* Custom BrowseButton for holding textFieldIndex
*/
private class BrowseButton extends JButton
{
private int textFieldIndex;
public BrowseButton( String text, int textFieldIndex )
{
super( text );
this.textFieldIndex = textFieldIndex;
}
public int getTextFieldIndex()
{
return textFieldIndex;
}
}
}