Home > Software engineering >  How to add JTextField whenever the button is clicked?
How to add JTextField whenever the button is clicked?

Time:04-09

I am practising Java Swing and I am trying to create a GPA calculator. I am having a hard time with my code, how can I add text fields whenever the JButton "add" is clicked? I also want the text fields to align vertically when the button is clicked. Should I use a layout or something?

You can check my screenshot as well.

screenshot

Here is my code:

import java.awt.event.ActionEvent;
import javax.swing.*;
public class gwa implements ActionListener, java.awt.event.ActionListener{
public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    
    //button
    JButton buttonAdd = new JButton("Add");
    buttonAdd.setBounds(30, 30, 80, 34);
    buttonAdd.addActionListener(new gwa());
    
    //textfield
    JTextField gradeField = new JTextField();
    gradeField.setBounds(150, 30, 100, 35);
    JTextField unitsField = new JTextField();
    unitsField.setBounds(300, 30, 100, 35);
    
    //panel
    panel.setLayout(null);
    panel.add(buttonAdd);
    panel.add(gradeField);
    panel.add(unitsField);

    //frame
    frame.add(panel);
    frame.setSize(500,500);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

@Override
public void actionPerformed(ActionEvent e) {

}

CodePudding user response:

One way – but not the only way – is to use animated gif of running app

CodePudding user response:

You should first give your button's Action event the panel, and then do the Action My English is not good, so I use translation software to answer, please forgive me

  • Related