Hi,
I want to draw a rectangle but I want a user to specify its dimensions.
Currently, I have 4 JTextAreas that take x, y, width and height values.
I also have a button. I know how to display those values etc but I don't know how to link them to my draw method.
I spend a lot of time trying to solve it so any help is appreciated.
The code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*; // Needed for ActionListener
class MyGui4 extends JFrame {
private JTextField x = new JTextField(3);
private JTextField y = new JTextField(3);
private JTextField width = new JTextField(3);
private JTextField height = new JTextField(3);
private JPanel p = new JPanel(); //draw rectangle here
public MyGui4() {
JButton b = new JButton("Draw");
b.addActionListener(new DrawRectangle());
x.addActionListener(new DrawRectangle());
y.addActionListener(new DrawRectangle());
width.addActionListener(new DrawRectangle());
height.addActionListener(new DrawRectangle());
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(new JLabel("X"));
content.add(x);
content.add(new JLabel("Y"));
content.add(y);
content.add(new JLabel("Width"));
content.add(width);
content.add(new JLabel("Height"));
content.add(height);
content.add(b);
content.add(new JLabel("Your Rectangle"));
content.add(p);
setContentPane(content);
pack();
setTitle("Rectangel Painter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
class DrawRectangle implements ActionListener {
public void actionPerformed(ActionEvent e) {
String temp1 = x.getText();
int xVar = Integer.parseInt(temp1);
String temp2 = y.getText();
int yVar = Integer.parseInt(temp2);
String temp3 = width.getText();
int widthVar = Integer.parseInt(temp3);
String temp4 = height.getText();
int heightVar = Integer.parseInt(temp4);
Rectangle rect = new Rectangle(xVar,yVar,widthVar,heightVar);
rect.getX();
rect.getY();
rect.getWidth();
rect.getHeight();
//?????
//rect(p);
}
}
public static void main(String[] args) {
MyGui4 window = new MyGui4();
window.setVisible(true);
}
}