【发布时间】:2011-12-01 17:31:55
【问题描述】:
我想知道如何创建一个方法,在单独的窗口中打开一个新的 jframe,让我可以搜索信息。目前我有一个按钮说单击我,但是,我想输入一个事件,一旦单击它,它将打开一个新窗口,用户可以输入字符串来搜索信息。我应该为 Jframe 创建一个新类吗?任何提示和代码将不胜感激。谢谢!
【问题讨论】:
我想知道如何创建一个方法,在单独的窗口中打开一个新的 jframe,让我可以搜索信息。目前我有一个按钮说单击我,但是,我想输入一个事件,一旦单击它,它将打开一个新窗口,用户可以输入字符串来搜索信息。我应该为 Jframe 创建一个新类吗?任何提示和代码将不胜感激。谢谢!
【问题讨论】:
这取决于您将在第二个窗口中拥有的功能列表,如果功能列表相当扩展,那么最好将其设置为单独的类,即使 JDialog 也不需要 JFrame。
下面的示例代码显示了如何在单击按钮时打开 JDialog:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TestFrameOnFrame extends JFrame implements ActionListener{
public TestFrameOnFrame(){
JButton button = new JButton("Show New Frame");
button.addActionListener(this);
this.add(button);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog(this);
dialog.setTitle("Search Dialog");
dialog.add(new JLabel("Just a test"));
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
public static void main(String[] args) {
new TestFrameOnFrame();
}
}
【讨论】:
JFrame frame = new JFrame("Search Frame");?
建议:
【讨论】:
根据“第二帧”的复杂性,您可以使用内部类,也可以将其分开。无论哪种方式,只需让按钮上的事件侦听器启动这个新类的实例,它要么是,要么创建一个新的 Jframe,并将其设置为可见。
【讨论】: