Search code examples
javaswingjframejbuttonjtextarea

To add JButton to JTextArea


How can I add JButton on JTextArea? I have such a code, when I print name of country in JTextField some information using REST displays on JTextArea. But I want to use for this purpose JButton. When user click JButton information will be start searching and then display.

public class Client extends JPanel implements ActionListener{

protected JTextField textField;
protected JTextArea textArea;
protected static JButton search;

public Client() {
    super(new GridBagLayout());

    search = new JButton("Search");
    search.setBounds(100,190,60,30);

    textField = new JTextField(20);
    textField.addActionListener(this);

    textArea = new JTextArea(10, 20);
    textArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textArea);

    GridBagConstraints c = new GridBagConstraints();
    c.gridwidth = GridBagConstraints.REMAINDER;

    c.fill = GridBagConstraints.HORIZONTAL;
    add(textField, c);

    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 1.0;
    add(scrollPane, c);
}

My program show such a window, I want to place my button on the bottom of the window (on the picture).

enter image description here


Solution

  • I don't know what are you expecting exactly, but I wrote this code, I'm not use your code, cause I can't run it, but I think this is that you want.

    JFrame gui = new JFrame("Button on bottom.");
    
    JPanel panel = new JPanel(new BorderLayout());
    
    JTextField textfield = new JTextField();
    textfield.setText("Australia");
    
    JTextArea textarea = new JTextArea();
    textarea.setText("Australia, -27, 133. AUD");
    
    JButton button = new JButton("Button on bottom.");
    button.setFont(new java.awt.Font("Dialog", 0, 15));
    button.setBorderPainted(false);
    button.setFocusable(false);
    button.setForeground(new java.awt.Color(255, 255, 255));
    button.setBackground(new java.awt.Color(0, 140, 255));
    
    panel.add(textfield, BorderLayout.PAGE_START);
    panel.add(textarea);
    panel.add(button, BorderLayout.PAGE_END);
    
    gui.setDefaultCloseOperation(gui.EXIT_ON_CLOSE);
    gui.setSize(300, 300);
    gui.setLocationRelativeTo(null);
    gui.add(panel);
    gui.setVisible(true);}}