javajbuttonjtextfieldjfilechooser

How to put a JButton inside a JTextField (Java)?


I would like to have a JButton (with a folder icon image) inside a JTextField, like over on the far right of the JTextField, so that when clicked, the button opens up a JFileChooser, and when a file is selected, the path to the file appears inside the JTextField.

I have made this code, but nothing shows up.

public class TextFieldChooser extends JTextField {

    public ImageIcon folderIcon;
    public JButton btnFolder;

    public TextFieldChooser(int columns) {
        super(columns);
        btnFolder = new JButton();
        folderIcon = new ImageIcon(getClass().getResource("/resources/folder_find.png"));
        btnFolder.setIcon(folderIcon);
        this.add(btnFolder);

    }
}

Solution

  • Building on what Shakedown suggested, I think you can get the desired effect relatively easily. What you do is have a JPanel that contains both the text area and, beside it, the button. Next, set the text field to not draw any borders and give the JPanel a bevel border. Now it will look like the button is inside the text area. It might take some fine tuning, but it should work.