Asked  6 Months ago    Answers:  5   Viewed   22 times

I seem to have a problem with my very simple implementation of a file chooser dialogue that requires me to minimize Netbeans each time in order to get to it, and it gets pretty frustrating specially now with testing.

I have seen a few solutions online including SO yet none seem to do the trick, while some other seem very lengthy and complicated for my current level.

private void fileSearch() {

    JFileChooser fileSelect = new JFileChooser();
    int returnVal = fileSelect.showOpenDialog(null);
    String pathToFile;

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileSelect.getSelectedFile();
        pathToFile = file.getAbsolutePath();
        try {
            P.binaryFileToHexString(pathToFile);
        } catch (Exception e) {
            System.out.print("Oops! there was an error there..." + e);
        }
        System.out.println("nYou chose to open this file: " + file.getName());
    }
}

Some of my try's include using;

.requestFocus();
.requestFocusInWindow();
.setVisible();

Is there a particular attribute/method I can set in order to solve the problem?

 Answers

73

The API for showOpenDialog() refers to showDialog(), which says, "If the parent is null, then the dialog depends on no visible window, and it's placed in a look-and-feel-dependent position such as the center of the screen."

The example below positions the chooser in the center of the screen on my L&F. You might see how it compares to yours.

package gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;

/**
 * @see http://stackoverflow.com/questions/8507521
 * @see http://stackoverflow.com/questions/5129294
 */
public class ImageApp extends JPanel {

    private static final int MASK =
        Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
    private JFileChooser chooser = new JFileChooser();
    private Action openAction = new ImageOpenAction("Open");
    private Action clearAction = new ClearAction("Clear");
    private JPopupMenu popup = new JPopupMenu();
    private BufferedImage image;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ImageApp().create();
            }
        });
    }

    public void create() {
        JFrame f = new JFrame();
        f.setTitle("Title");
        f.add(new JScrollPane(this), BorderLayout.CENTER);
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File");
        menu.setMnemonic('F');
        menu.add(new JMenuItem(openAction));
        menu.add(new JMenuItem(clearAction));
        menuBar.add(menu);
        f.setJMenuBar(menuBar);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setSize(new Dimension(640, 480));
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public ImageApp() {
        this.setComponentPopupMenu(popup);
        popup.add("Popup Menu");
        popup.add(new JMenuItem(openAction));
        popup.add(new JMenuItem(clearAction));
    }

    @Override
    public Dimension getPreferredSize() {
        if (image == null) {
            return new Dimension();
        } else {
            return new Dimension(image.getWidth(), image.getHeight());
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
    }

    private class ClearAction extends AbstractAction {

        public ClearAction(String name) {
            super(name);
            this.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C);
            this.putValue(Action.ACCELERATOR_KEY,
                KeyStroke.getKeyStroke(KeyEvent.VK_C, MASK));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            image = null;
            revalidate();
            repaint();
        }
    }

    private class ImageOpenAction extends AbstractAction {

        public ImageOpenAction(String name) {
            super(name);
            this.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_O);
            this.putValue(Action.ACCELERATOR_KEY,
                KeyStroke.getKeyStroke(KeyEvent.VK_O, MASK));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            int returnVal = chooser.showOpenDialog(chooser);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File f = chooser.getSelectedFile();
                try {
                    image = ImageIO.read(f);
                    revalidate();
                    repaint();
                } catch (IOException ex) {
                    ex.printStackTrace(System.err);
                }
            }
        }
    }
}
Tuesday, June 1, 2021
 
mistero
answered 6 Months ago
39
import ctypes

text = 'Using MB_SYSTEMMODAL'
title = 'Some Title'

ctypes.windll.user32.MessageBoxW(0, text, title, 0x1000)

MB_SYSTEMMODAL (0x1000) has the WS_EX_TOPMOST (0x40000) style.

The MessageBoxEx function seems to work good with using just the WS_EX_TOPMOST (0x40000) style.

import ctypes

text = 'Using WS_EX_TOPMOST'
title = 'Some Title'

ctypes.windll.user32.MessageBoxExW(0, text, title, 0x40000)

The MessageBox function has no parameters to change size. Perhaps an alternative like tkinter or another gui toolkit might be able to change messagebox size (though it maybe not if it just a wrapper for MessageBoxW) or you could perhaps create a custom window to use.

See MSDN MessageBox function for values to use.

See also MSDN MessageBoxEx function.

Thursday, August 5, 2021
 
Vincent Stimper
answered 4 Months ago
100

The short answer should be, what have you tried? The long answer is yes...

JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new FileFilter() {

    @Override
    public boolean accept(File f) {
        String name = f.getName().toLowerCase();
        return (name.endsWith(".png") &&
                        name.endsWith(".jpg") &&
                        name.endsWith(".gif") &&
                        name.endsWith(".bmp") &&
                        f.length() < 3 * (1024 * 1024));
    }

    @Override
    public String getDescription() {
        return "Images < 3mb";
    }
});

Technically, you can filter on any property or combination of properties from File

Friday, August 20, 2021
 
viper
answered 4 Months ago
44

Try to use this

    self.windowController?.showWindow(nil)
    self.makeKeyAndOrderFront(self)
    NSApp.activate(ignoringOtherApps: true)
Sunday, August 29, 2021
 
showstealer
answered 3 Months ago
24

the problem is the type of InputMap: by default (that is without parameter), that's WHEN_FOCUSED. As the chooser itself is rarely focused, the binding will not be found. Instead bind in WHEN_ANCESTOR...

       pane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
           .put(KeyStroke.getKeyStroke("F1"), "damned");

As you see here, I replaced the SPACE by F1: the space is needed (and thus eaten) by the textfield which takes the name input

Friday, November 26, 2021
 
Ekkehard.Horner
answered 3 Days ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share