请查看以下代码
Main.Java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame
{
private JButton ok;
public Main()
{
ok = new JButton("OK");
ok.addActionListener(new ButtonAction());
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(ok);
getContentPane().add(panel,"South");
this.setVisible(true);
this.setSize(new Dimension(200,200));
this.validate();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new Main();
}
catch(Exception e)
{
}
}
private class ButtonAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
Dialog d = new Dialog();
d.setVisible(true);
}
}
}
Dialog.java
import java.awt.Event;
import java.awt.*;
import javax.swing.*;
public class Dialog extends JDialog
{
private JButton done;
public Dialog()
{
done = new JButton("Done");
this.add(done);
this.setSize(new Dimension(400,200));
}
}
在这里,我想将“对话”表单“附加”到主表单。这意味着,当我单击Main.Java中的OK按钮时,Dialog表单将附加到主窗体的右侧。因此,当我移动主窗体时,对话框也会移动。但是,对话框表单应该是独立的,这意味着,当我单击对话框中的“x”按钮时,只存在该表单,而不是主表单。
单击按钮时,如何将此对话框表单附加到主表单的右侧?请帮忙!
答案 0 :(得分:2)
答案不是MouseListener,而是ComponentListener。我设法使用该侦听器的“componentMoved()”方法。
Main.java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame implements ComponentListener, ActionListener
{
private JButton ok;
private Dialog dialog;
public Main()
{
ok = new JButton("OK");
ok.addActionListener(this);
dialog = new Dialog();
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(ok);
getContentPane().add(panel,"South");
this.addComponentListener(this);
this.setVisible(true);
this.setSize(new Dimension(200,200));
this.validate();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new Main();
}
catch(Exception e){}
}
public void actionPerformed(ActionEvent ae)
{
dialog.setVisible(true);
}
@Override
public void componentHidden(ComponentEvent arg0) {}
@Override
public void componentMoved(ComponentEvent arg0)
{
int x = this.getX() + this.getWidth();
int y = this.getY();
dialog.setDialogLocation(x, y);
}
@Override
public void componentResized(ComponentEvent arg0) {}
@Override
public void componentShown(ComponentEvent arg0) {}
}
Dialog.java
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JDialog;
public class Dialog extends JDialog
{
private JButton done;
public Dialog()
{
done = new JButton("Done");
this.add(done);
this.setSize(new Dimension(400,200));
}
public void setDialogLocation(int x, int y)
{
this.setLocation(x, y);
}
}
答案 1 :(得分:0)
我不知道任何内置函数你只能说“dialog.moveWithThisOtherWindow(otherWindow)”或其他一些这样的东西,它就会发生。您必须自己编写代码才能完成此操作。
在父窗体上创建鼠标侦听器或鼠标适配器。在鼠标侦听器中的“鼠标移动”事件中,移动子窗体。当然,父母必须有一个孩子的句柄。根据您创建窗口的方式,您可能需要某种“注册”功能,孩子可以调用该功能以向父母表明身份。