I have this exercise in my textbook:
In this exercise, you will explore a simple way of visualizing a Rectangle object. The setBounds method of the JFrame class moves a frame window to a given rectangle. Complete the following program to visually show the translate method of the Rectangle class:
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class TranslateDemo
{
public static void main(String[] args)
{
// Construct a frame and show it
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// Your work goes here: Construct a rectangle and set the frame bounds
JOptionPane.showMessageDialog(frame, "Click OK to continue");
// Your work goes here: Move the rectangle and set the frame bounds again
}
}****
I tried this but it's not working:
**import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class TranslateDemo
{
public static void main(String[] args)
{
// Construct a frame and show it
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// Your work goes here: Construct a rectangle and set the frame bounds
Rectangle box = new Rectangle(10, 20, 30, 40);
System.out.println("");
System.out.println(box);
System.out.println("");
JFrame f=new JFrame();
f.setBounds(50, 50, 200 ,200);
JOptionPane.showMessageDialog(frame, "Click OK to continue");
// Your work goes here: Move the rectangle and set the frame bounds again
box.translate(0,30);
System.out.println(box);
JOptionPane.showMessageDialog(frame, "Click OK to continue");
}
}**
Can you please help me ?
Let's start with the fact that you've created two instance of
JFrame
...The first is what's visible on the screen and the second is not.
Maybe something like...
will work better.
Any changes you make to
box
won't change the frame, asJFrame
uses the properties ofRectangle
to set its properties and doesn't maintain a reference to the originalRectangle
, instead, you will need callsetBounds
again in order to update frameAs a general rule though, you shouldn't be setting the size the frame itself, but instead, rely on
pack
, but since this is an exercise, I can overlook it ;)