Я пытаюсь изменить изображение, отображаемое в JLabel
моего пользовательского интерфейса.
Следующий класс - очень простая проверка концепции. Пользовательский интерфейс берет папку, полную изображений (поле imageFolderPath
) и отображает первое изображение с измененным размером, только в JLabel
; щелчок по изображению побуждает пользовательский интерфейс отобразить в папке следующее изображение.
По крайней мере, так и должно быть. На самом деле изображение не отображается. Ошибка, очевидно, связана с методом reloadImage()
, либо при изменении масштаба изображения, либо при перерисовке JLabel
, но мне не удалось найти или исправить проблему. Есть идеи?
public class Test extends JFrame {
private JPanel contentPane;
private JLabel boardImage;
private ImageIcon icon;
public String imageFolderPath = "C:\\modify\\it\\to\\suit\\your\\needs\\";
public File[] files;
public int indexImage = 0;
public int imageResolution = 450;
// =========================================================
// TODO | Constructors
/**
* Create the frame.
*/
public Test() {
if( !new File(imageFolderPath).exists() )
new File(imageFolderPath).mkdir();
this.files = new File(imageFolderPath).listFiles();
System.out.println("Can show:");
for( File file : files )
System.out.println("\t"+file.getName());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, imageResolution, imageResolution);
contentPane = new JPanel();
contentPane.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
// Every time the image is clicked, another one is shown
indexImage++;
reloadImage();
}
});
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
boardImage = new JLabel();
boardImage.setBounds(0, 0, imageResolution, imageResolution);
reloadImage();
contentPane.add(boardImage);
}
// =========================================================
// TODO | Support methods
/** Reloads the image of the {@link ChessBoard} at its current state. */
public void reloadImage() {
if( files[indexImage % files.length].exists() )
System.out.println("The file " + files[indexImage % files.length].getName() + " exists");
else System.out.println("The file " + files[indexImage % files.length].getName() + " doesnt exists");
// Reload the image - resized
BufferedImage buffer = null;
try {
buffer = ImageIO.read( files[indexImage % files.length] );
} catch (IOException e) { e.printStackTrace(); }
Image rescaledImage = buffer.getScaledInstance(imageResolution, imageResolution, Image.SCALE_SMOOTH);
icon = new ImageIcon(rescaledImage);
boardImage = new JLabel(icon);
// boardImage.setText( files[indexImage % files.length].getName() );
System.out.println("Is now showing " + files[indexImage % files.length].getName() );
boardImage.repaint();
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}