In: Computer Science
Use Java GUI create following:
Task 1: A basic UI with a button and a TextField, when you press the button, set the button text to the current text field contents.
Task 2: set the text field text to the mouse coordinates when that same button is pushed.
Task1
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 GUI {
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(220, 50, 100, 30);
JButton convert = new JButton();
convert.setText("Click");
convert.setBounds(200, 150, 100, 20);
convert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
str.setText(e.getActionCommand());
}
});
panel.add(str);
panel.add(convert);
frame.add(panel);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Task2:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GUI {
static JFrame frame = new JFrame("JFrame Example");
static JTextField str = new JTextField(10);
static int x,y;
public static void main(String s[]) {
JPanel panel = new JPanel();
panel.setLayout(null);
str.setBounds(220, 50, 100, 30);
JButton convert = new JButton();
convert.setText("Click");
convert.setBounds(200, 150, 100, 20);
convert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
str.setText(x+","+y);
}
});
frame.addMouseListener(new MouseListenerImpl());
panel.add(str);
panel.add(convert);
frame.add(panel);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class MouseListenerImpl implements MouseListener{
@Override
public void mouseClicked(MouseEvent aE) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent aE) {
GUI.x=aE.getX();
GUI.y=aE.getY();
System.out.println(GUI.x);
System.out.println(GUI.y);
}
@Override
public void mouseExited(MouseEvent aE) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent aE) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent aE) {
// TODO Auto-generated method stub
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
Please Like and Support me as it helps me a lot