Button does not appear in window

Asked

Viewed 358 times

1

My button called btnLimpar does not appear. that’s the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Frame extends JFrame {
    private JButton btnEnviar = new JButton("EnviarMSG");
    private JButton btnLimpar = new JButton("Limpar");
    private JTextField txtCampo = new JTextField();
    private JLabel lblExibir = new JLabel();

    public Frame() {
        super("Meu JFrame executado em terminal");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(getOwner());
        setSize(400, 330);
        setVisible(true);
        setLayout(null);

        txtCampo.setFont(new Font("arial", Font.PLAIN,40));
        txtCampo.setBounds(15, 20, 360, 70);
        add(txtCampo);

        btnEnviar.setBounds(210 ,110, 170, 70);
        add(btnEnviar);

         btnEnviar.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

          lblExibir.setText(txtCampo.getText());

            }
        });

        btnLimpar.setBounds(210 ,110, 170, 70);
        add(btnLimpar);

        btnLimpar.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                lblExibir.setText(null);
                txtCampo.setText(null);
                txtCampo.requestFocus();                        
            }       
        });

        lblExibir.setFont(new Font("arial", Font.PLAIN, 20));
        lblExibir.setOpaque(true);
        lblExibir.setBackground(Color.gray);
        lblExibir.setForeground(Color.red);
        lblExibir.setBounds(15, 220, 360, 70);
        add(lblExibir);
    }

    public static void main(String[] args) {
        new Frame();
    }
}

Print

1 answer

1


One button is on top of the other, because by creating them you have set the same position of them within your Jframe:

btnEnviar.setBounds(210 ,110, 170, 70);

...

btnLimpar.setBounds(210 ,110, 170, 70);

A possible solution is to change the position of btnLimpar thus:

btnLimpar.setBounds(20 ,110, 170, 70);

Where the parameters are:

setBounds(int x, int y, int largura, int altura);

x and y are the coordinates of the plane of the position of the element.

Upshot:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.