//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.plaf.metal.MetalFileChooserUI;

public class MetalFileChooserBugDemo {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                // 1) Force Metal Look & Feel
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                // 2) Tell Swing to use MetalFileChooserUI for JFileChooser
                UIManager.put("FileChooserUI", "javax.swing.plaf.metal.MetalFileChooserUI");
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            JFrame frame = new JFrame("MetalFileChooserUI Save‑Mode Bug Demo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new FlowLayout(FlowLayout.CENTER));
            frame.add(new JButton(new AbstractAction("Replicate Save Bug") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    replicateBug(frame);
                }
            }));
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }

    private static void replicateBug(Component parent) {
        // Now when we construct it, JFileChooser will pick up your override
        JFileChooser fc = new JFileChooser();
        // Re-install the UI to pick up our UIManager override
        fc.updateUI();

        // Create a new file to save
        fc.setSelectedFile(new File(fc.getCurrentDirectory().getAbsolutePath(),"fakeFile.txt"));

        // 1) Start in DIRECTORIES_ONLY
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        // 2) Then switch to FILES_ONLY
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

        // 3) Show Save dialog
        File sel = fc.getSelectedFile();
        JOptionPane.showMessageDialog(parent,
                "You chose:\n" + sel.getAbsolutePath() + " \nbut the dialog sees\n" + ((MetalFileChooserUI)fc.getUI()).getFileName(),
                "Selection", JOptionPane.INFORMATION_MESSAGE);
        fc.showSaveDialog(parent);
    }
}