How to put a JButton inside a JTextField (Java)? - 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);
}
}

You may find the Component Border helpfull. It allows you to display a button in the text field by using the Border API.

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.

You can't don't want to put a button in a text field. You need to break out your intent into several components - 3, in fact.
First you're going to need a parent container, or something that will contain both your text field and also the button; a JPanel should suffice.
Then you need your real components, and by real I mean the ones that actually do something. These are your JTextField and JButton - go ahead and add these to the JPanel. In order to add them and have them appear how you want (with the button in the corner), you're going to need to specify a layout for your JPanel. This layout will define where added components go (visually) inside the JPanel.
Now that you've added those things into your JPanel, you can work only with your JPanel instead of thinking in terms of the contained JTextField and JButton.

Because Pyrite has not posted his final solution, here is mine:
my_button = new JButton("x");
JFormattedTextField my_textfield = new JFormattedTextField("Nr.");
my_textfield.setBorder(javax.swing.BorderFactory.createEmptyBorder());
JPanel textfield_with_button = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
Border lowered_bevelborder = BorderFactory.createLoweredBevelBorder();
textfield_with_button.setBorder(lowered_bevelborder);
textfield_with_button.add(my_textfield);
textfield_with_button.add(my_button);

Well I probably think you got your answer, but for others who want to do this easily, cuz I think the other answers are a bit too complicated.
So, what you need to do is, when you create the JTextField you create the JButton as well. Well see the code for yourself:
JButton button = new JButton();
button.setBounds(50, 5, 50, 25);
button.setBackground(Color.black);
JTextField textField = new JTextField();
textField.setBounds(20, 60, 100, 35);
textField.setBackground(Color.white);
textField.add(button);
And its that easy, I used setBounds() on the button cuz I can place it anywhere I want, as for the textField you can use a frame/panel layout aswell, but this was for just demonstrating how it works.

Related

Adding a certain image to a JPanel in Java

So, I want to draw an image based on the current selection of a scroll list in java Swing. It seems the best way to do this is to add an label to a panel. I tried multiple various ways of doing this and for the life of me I can't figure why it won't display the image. This is a snippet of what I have managed to do so far.
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
ImageIcon greenDragon = new ImageIcon("C:\\Users\\Ilmari\\Documents\\NetBeansProjects\\GUI harkkatyƶ\\src\\Ile\\Green_dragon.png");
JLabel dragon = new JLabel();
dragon.setIcon(greenDragon);
String selectedMonster = jList1.getSelectedValue();
if(selectedMonster.equals("Green Dragon")){
jPanel1.add(dragon);
}
else if(selectedMonster.equals("Black Demon")){
}
}
The best outcome so far has been overriding the background JLabel image completely and only displaying a white box with the image.
JLabel dragon = new JLabel();
This label should be declared as an attribute of the class, and added to the GUI when it is first made. Then in the jList1MouseClicked method, simply call dragon.setIcon(..).
That way there is no need to revalidate the GUI on each image change.
On the subject of jList1MouseClicked: Use the most optimized listener for a JList. A ListSelectionListener will react to keyboard input as well as mouse input, and provides other advantages besides.
If the image isn't displayed at all. You need to revalidate and repaint your frame.
To achieve that - add this to your code:
frame.getContentPane().validate();
frame.getContentPane().repaint();

Removing a label in Java

I have this piece of code, which should remove a label, when a button is pressed:
final JLabel label = new JLabel("Label text");
rightPanel.add(label);
final JButton remove = new JButton("Remove label");
leftPanel.add(remove);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
rightPanel.remove(label);
}
});
But when I click on the button, it doesn't remove the label text. Only when I resize the window (for example set it to full screen), the label text dissapears.
From this previous answer located here, put forth by camickr, you need to do the following:
The code would be (assuming the use of a JPanel):
panel.remove(...);
panel.revalidate();
panel.repaint(); // sometimes needed
You need to remove the component and then tell the panel to layout the remaining components.
Perhaps not an answer to your question but what I consider helpful advice: only add/remove components when it is absolutely necessary. If you get creative, you'll find that there are often better solutions than adding/removing components. For example, instead of removing a JButton, consider disabling it instead.
In your situation, you could always just do label.setText(""). This way you don't need to revalidate() and repaint().
I very rarely call revalidate() and repaint() in my code. I think it's better to update the existing components than to remove/add them.

Adding a button anywhere in a JPanel

Without using the Swing GUI on Eclipse, I've been struggling with adding a button to a JFrame anywhere in the frame (so no BorderLayout.CENTER). I can't get past:
JPanel panel = new JPanel();
JButton OKButton = new JButton("OK");
OKButton.addActionListener(new MyAction());
panel.add(OKButton,BorderLayout.CENTER);
So would something like this be completely redesigned or is there something I'm missing?
EDIT: By Anywhere (as I'm planning to add more than one button/label to a frame), I meant perhaps a coordinate on the frame. So other than dead center, (example) 75% from the left and 25% down.
You can use different Panels with different LayoutMangers to arrange the GUI as you like.
Have a look here for some common LayoutManagers:
http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
Otherwise you could use the null Layout (panel.setLayout(null)) and place all components by setting the position. But I would recommend you the LayoutMangers

why aren't my JLabels and JTextFields showing up in the JPanel?

I have a JDialog and inside it I have a JPanel that uses FlowLayout
now I've created 3 labels and text fields using the Netbeans GUI Builder, and I want to add 2 more text fields using code
I've adjusted the size of the panel so that when I add a new label and a textfield with a preferred size the new set of label - textfield will be under the previous set
somewhere in the JDialog I do something like this
JLabel cores = new JLabel("Cores");
cores.setPreferredSize(new Dimension(70,15));
first = new JTextField();
first.setPreferredSize(new Dimension(140,20));
JLabel power = new JLabel("Power");
power.setPreferredSize(new Dimension(70,15));
second = new JTextField();
second.setPreferredSize(new Dimension(140,20));
panel2.add(cores);panel2.add(first);panel2.add(power);panel2.add(second);
when I compile the program, the labels don't show up and neither do the textfields
when I go down and click I have the following result
http://img684.imageshack.us/img684/13/unledlpy.png
if I type something, the text field appears
http://img5.imageshack.us/img5/6796/unledhig.png
the labels don't appear though, I don't think I made any changes to the properties, any help would be appreciated thanks
Define the no of columns while creating object.
like this
JTextField jt=new JTextField(20);

setBorder on JTextField does not work ? or does it?

The code is like this:
JTextField txt = new JTextField();
txt.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.red));
However the text field is ignoring my call to setBorder.
No changes whatsoever.
I were to replace it with a JLabel (for instance)
JLabel txt = new JLabel();
txt.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.red));
I would see the red border.
Can anybody tell me why? Or even better explain to me how to add a border in the JTextField?
Check out this explanation/recommendation from the Java API
In general, when you want to set a
border on a standard Swing component
other than JPanel or JLabel, we
recommend that you put the component
in a JPanel and set the border on the
JPanel.
So... you should nest your JTextField in a JPanel or JLabel, and put the border on the JPanel or JLabel. Voila!

Categories