我的教科书中有这个练习:
在本练习中,您将探索一种可视化 Rectangle 对象的简单方法。这JFrame 类的 setBounds 方法将框架窗口移动到给定的矩形。完成以下程序以直观地显示矩形.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
}
}****
我试过这个,但它不起作用:
**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");
}
}**
你能帮帮我吗?
让我们从您已经创建了两个JFrame
实例的事实开始......
// First instance
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
// Second instance
JFrame f=new JFrame();
f.setBounds(50, 50, 200 ,200);
第一个是屏幕上可见的内容,第二个不是。
也许像...
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);
f.setBounds(box);
会更好地工作。
您对box
所做的任何更改都不会更改框架,因为JFrame
使用 Rectangle
的属性来设置其属性,并且不维护对原始Rectangle
的引用,相反,您将需要再次调用setBounds
才能更新框架
作为一般规则,您不应该设置框架本身的大小,而是依靠pack
,但由于这是一个练习,我可以忽略它;)