我设计了java桌面应用程序 在我按下按钮的那个应用程序中 显示另一个Jframe绘制树 但当我关闭Jframe时,整个操作都很接近 但我只想关闭那个Jfarme我该怎么办? 这是jframe代码:
public class DrawTree extends JFrame{
public int XDIM, YDIM;
public Graphics display;
@Override
public void paint(Graphics g) {} // override method
// constructor sets window dimensions
public DrawTree(int x, int y)
{
XDIM = x; YDIM = y;
this.setBounds(0,0,XDIM,YDIM);
this.setVisible(false);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
display = this.getGraphics();
// draw static background as a black rectangle
display.setColor(Color.black);
display.fillRect(0,0,x,y);
display.setColor(Color.red);
try{Thread.sleep(500);} catch(Exception e) {} // Synch with system
} // drawingwindow
public static int depth(BinaryNode N) // find max depth of tree
{
if (N==null) return 0;
int l = depth(N.left);
int r = depth(N.right);
if (l>r) return l+1; else return r+1;
}
// internal vars used by drawtree routines:
private int bheight = 50; // branch height
private int yoff = 30; // static y-offset
// l is level, lb,rb are the bounds (position of left and right child)
private void drawnode(BinaryNode N,int l, int lb, int rb)
{
if (N==null) return;
try{Thread.sleep(100);} catch(Exception e) {} // slow down
display.setColor(Color.green);
display.fillOval(((lb+rb)/2)-10,yoff+(l*bheight),20,20);
display.setColor(Color.red);
display.drawString(N.element+"",((lb+rb)/2)-5,yoff+15+(l*bheight));
display.setColor(Color.blue); // draw branches
if (N.left!=null)
{
display.drawLine((lb+rb)/2,yoff+10+(l*bheight),((3*lb+rb)/4),yoff+(l*bheight+bheight));
drawnode(N.left,l+1,lb,(lb+rb)/2);
}
if (N.right!=null)
{
display.drawLine((lb+rb)/2,yoff+10+(l*bheight),((3*rb+lb)/4),yoff+(l*bheight+bheight));
drawnode(N.right,l+1,(lb+rb)/2,rb);
}
} // drawnode
public void drawtree(BinaryNode T)
{
if (T==null) return;
int d = depth(T);
bheight = (YDIM/d);
display.setColor(Color.white);
display.fillRect(0,0,XDIM,YDIM); // clear background
drawnode(T,0,0,XDIM);
}}
和另一个问题
当我从我的树类中新建一个对象时,我想在所有按钮代码中访问该对象 所以,我应该定义或更好地说,我应该如何定义可以在我的所有代码中访问的对象?
答案 0 :(得分:2)
您应将默认关闭操作设置为HIDE_ON_CLOSE
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
建议: 请注意,使用DISPOSE_ON_CLOSE,如果这不是最后打开的JFrame,您仍然可以保持程序运行: (取自javadocs) 注意:当Java虚拟机(VM)中的最后一个可显示窗口被丢弃时,VM可能会终止。有关详细信息,请参阅AWT线程问题。
答案 1 :(得分:0)
您可以简单地隐藏JFrame。
this.hide();
编辑:对于上述情况:Youssef G的答案更好。
问题的第2部分。创建树类并在程序中传递对象,使其与同一树对象相同。不要创建一个新的。
例如:
Class A {
B b; //B object inside class A
Tree t; //Tree object inside class A
}
Class B {
Tree t; //Tree object inside class B
}
现在两个类中都有一个树对象。当代码在A类中运行时,您可以创建一个新的树,它是类b的树。然后说这个.t = b.t;
希望这有帮助。