首先,在你的应用程序中添加一个按钮,用于打开文件对话框。
然后,为按钮添加单击事件枣蚂咐处理函数,在函数中添加下面的代码:
void CYourAppDlg::OnBnClickedOpenfile()
{
CFileDialog dlg(TRUE, _T("txt"), _T("*.txt"), OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, _T("Text Files (*.txt)|*.txt|All Files (*.*)|*.*||"), this)
if (dlg.DoModal() == IDOK)
{
CString path = dlg.GetPathName()
// open the file or do something with the path
}
}
其中,第一个CFileDialog 的构造函数中的参数分别表示:
使用文件打开对话框而不是文件保存对话框
默认文件类型为 txt
默认文件扩展名为 txt
OFN_FILEMUSTEXIST 和 OFN_HIDEREADONLY 这两个标志表示文件必须存在并且隐藏只读文件
第五个参数为文件类型过滤器,该参数表示只显示 .txt 格式的文件。
在 dlg.DoModal() == IDOK 条件成立后,可以使用 dlg.GetPathName() 函数凳纯获取选择文件的路径. 然后可以根据需要打开文件或进行其他 *** 物巧作。
注意要在头文件中包含 <afxwin.h>和 <afxdlgs.h>,才能使用CFileDialog.
Resourcesresources
=
getResources()//获得res资源对象Configuration
config
=
resources.getConfiguration()//获得设置对象DisplayMetrics
dm
=
resources
.getDisplayMetrics()//获得屏幕参数:主要是渗段分丛坦誉辨率,像素等。config.locale
=
Locale.SIMPLIFIED_CHINESE
//信没简体中文resources.updateConfiguration(config,
dm)
JButton btn=new JButton(new AbstractAction("关闭并打开") { 梁带春 @Override public void actionPerformed(ActionEvent e) { oldFrame.dispose()// 关闭并销毁,无需销毁可采用oldFrame.setVisible(false) newFrame.setVisible(true)// 行运打开新窗口 橡耐 }})import javax.swing.*
import java.awt.Rectangle
import java.awt.event.*
public class Swing7 extends JFrame implements ActionListener {
JButton jb = new JButton()
public Swing7() {
this.setTitle("Java——")
jb.setText("确定")
jb.setMnemonic('a')
this.add(jb)
this.setBounds(200, 300, 250, 300)
ctionListener就是Swing7实例。
}
public void actionPerformed(ActionEvent e) {// 实现ActionListener接口的actionPerformed接口。
JFrame frame = new JFrame("新窗口")//构造一个新的JFrame,作为新窗口。
frame.setBounds(// 让新窗口与Swing7窗口示例错开50像素。
new Rectangle(
(int) this.getBounds().getX() + 50,
(int) this.getBounds().getY() + 50,
(int) this.getBounds().getWidth(),
(int) this.getBounds().getHeight()
)
)
JLabel jl = new JLabel()// 注意类名别写错了。
frame.getContentPane().add(jl)
jl.setText("这是新窗口")
jl.setVerticalAlignment(JLabel.CENTER)
jl.setHorizontalAlignment(JLabel.CENTER)// 注意方法名别写错了。
frame.setVisible(true)
}
public static void main(String args[]) {
Swing7 s = new Swing7()
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)