In: Computer Science
Write the code in Java:
1. Create a method that displays your name in the console. This method is void and takes no parameters. Make an app that runs the method in response to a button press.
2. Create a version of the method in #1 that takes the text (String) to be displayed as a parameter. Allow the user to enter the text in a dialog box or text field and display that text in the console. Be sure to trim() the text.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ButtonClick {
static JFrame frame = new JFrame("JFrame Example");
public static void main(String s[]) {
JPanel panel = new JPanel();
panel.setLayout(null);
JButton convert = new JButton();
convert.setText("Click");
convert.setBounds(200, 150, 100, 20);
convert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
printNameToConsole();
}
private void printNameToConsole() {
System.out.println("Uday");
}
});
panel.add(convert);
frame.add(panel);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Answer 2:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ReverseStringUI {
static JFrame frame = new JFrame("JFrame Example");
static JTextField str= new JTextField(10);
public static void main(String s[]) {
JPanel panel = new JPanel();
panel.setLayout(null);
str.setBounds(80, 50, 100, 30);
JButton convert = new JButton();
convert.setText("Print");
convert.setBounds(80, 150, 100, 20);
convert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
printName(str.getText());
}
private void printName(String aText) {
System.out.println(aText);
}
});
panel.add(str);
panel.add(convert);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me