Java swing duplicates the JTextField when resizing

0

Good, I've been studying a bit of user interface design in Java and I have a problem, the case is that when you add a text entry to a JPanel (With JTextField) and change the size of the window , several more cells are created, when I understand that this should not be so, do you think of where the error is?

import java.awt.*;

import javax.swing.*; 
public class AWTUserWriting {

public static void main(String args[]){

    Frame frame = new Frame();

}

}

class Frame extends JFrame{
public Frame(){
    setTitle("Hola Usuario");
    setSize(300, 400);
    setResizable(true);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    VentanaTexto text = new VentanaTexto();
    add(text);

}
}

class VentanaTexto extends JPanel{

public void paintComponent(Graphics g){     
    super.paintComponent(g);
    setLocation(0,300);
    JTextField textField = new JTextField(20);
    add(textField);
    JButton boton = new JButton("send");
    add(boton);
}
}
    
asked by angrymasther 26.01.2018 в 12:59
source

1 answer

1

Greetings angrymasther.

Your problem lies in the method paintComponent(Graphics g) of class VentanaTexto .

The reason why more components appear is because you are creating those new components in that method and then you are adding them to the panel. The paintComponent method is executed multiple times when changes occur in the main window (what calls the repaint() method) in this class, in this case, it will happen when you change the size of the window.

Also, do not use the paintComponent method to instantiate new components or adjust initial settings. That's what the class constructor is for.

To avoid this behavior, your class VentanaTexto should look like this:

class VentanaTexto extends JPanel{
    JTextField textField; // Los declaro aquí porque es posible que necesites usarlos más adelante en otro lugar de tu clase, o incluso fuera de este
    JButton boton;    

    public VentanaTexto() {
        setLocation(0,300);
        textField = new JTextField(20);
        add(textField);
        boton = new JButton("send");
        add(boton);
    }

    public void paintComponent(Graphics g){     
        super.paintComponent(g);
    }
}
    
answered by 26.01.2018 в 18:56