How do I add something written on a JList to JTextfield by clicking on a JButton?

36 Views Asked by At

I'm making a program to insert users into a PostgreSQL database using NetBeans, and recently I've faced a problem that I'm asking myself if it's possible to fix? Basically, I wanted to select something from a JList and put it into a JTextField. Is it possible? I've tried a lot of ways to do it and nothing's working.

here's the interface i did:

Code:

Code2:

Code3:

1

There are 1 best solutions below

0
Abra On

Here is a simple Swing application that displays a JTextField, a JList and a JButton.

When you click on the JButton the selected item in the JList is copied to the JTextField. (Refer to method setTextFieldText in the below code.)

Note that the ActionListener is implemented using a method reference.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class ShirleyB {
    private JList<String> list;
    private JTextField textField;

    private void buildAndDisplayGui() {
        JFrame frame = new JFrame("Shirley B");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createTextField(), BorderLayout.PAGE_START);
        frame.add(createList(), BorderLayout.CENTER);
        frame.add(createButton(), BorderLayout.PAGE_END);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private JPanel createButton() {
        JPanel panel = new JPanel();
        JButton button = new JButton("Add");
        button.addActionListener(this::setTextFieldText);
        panel.add(button);
        return panel;
    }

    private JScrollPane createList() {
        String[] items = new String[]{"Zeroth",
                                      "First",
                                      "Second",
                                      "Third",
                                      "Last"};
        list = new JList<>(items);
        JScrollPane scrollPane = new JScrollPane(list);
        return scrollPane;
    }

    private JPanel createTextField() {
        JPanel panel = new JPanel();
        textField = new JTextField(20);
        panel.add(textField);
        return panel;
    }

    private void setTextFieldText(ActionEvent event) {
        String selection = list.getSelectedValue();
        textField.setText(selection);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new ShirleyB().buildAndDisplayGui());
    }
}