
Akisha L.
asked 01/31/21Programing exercise
From our previous lessons. Try to convert the simple program in to a GUI program by using labels, text field and buttons.
Program Output
Enter name
Andrea [Enter]
Enter your age
24 [Enter]
Hello Andrea
You are 24 years old
1 Expert Answer

Patrick B. answered 01/31/21
Math and computer tutor/teacher
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Hello extends JPanel {
private JButton cmdButHELLO;
private JLabel jcomp2;
private JTextArea txtName;
private JLabel jcomp4;
private JTextArea txtAge;
private JLabel labelName;
private JLabel labelAge;
public Hello() {
//construct components
cmdButHELLO = new JButton ("SAY HELLO");
jcomp2 = new JLabel ("Input Name");
txtName = new JTextArea (5, 5);
jcomp4 = new JLabel ("Input Age");
txtAge = new JTextArea (5, 5);
labelName = new JLabel ("");
labelAge = new JLabel ("");
//adjust size and set layout
setPreferredSize (new Dimension (352, 146));
setLayout (null);
//add components
add (cmdButHELLO);
add (jcomp2);
add (txtName);
add (jcomp4);
add (txtAge);
add (labelName);
add (labelAge);
cmdButHELLO.addActionListener(
new ActionListener()
{
@Override public void actionPerformed(ActionEvent e)
{
labelName.setText("Hello " + txtName.getText());
labelAge.setText("You are " + txtAge.getText() + " years old ");
}
}
);
//set component bounds (only needed by Absolute Positioning)
cmdButHELLO.setBounds (245, 30, 105, 35);
jcomp2.setBounds (15, 15, 70, 25);
txtName.setBounds (90, 10, 145, 35);
jcomp4.setBounds (15, 55, 65, 25);
txtAge.setBounds (90, 50, 145, 30);
labelName.setBounds (20, 100, 150, 30);
labelAge.setBounds (200, 100, 150, 25);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("Hello");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new Hello());
frame.pack();
frame.setVisible (true);
}
}
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Patrick B.
source code posted in the RESROUCES section under this link01/31/21