java中怎样指定生成的窗口位置? 给个示例代码 谢~~~

 我来答
匿名用户
推荐于2016-11-22
展开全部
JFrame frame = new JFrame(“窗口位置”);
frame.setLocation(x,y);
frame.setVisible(true);

给你一个窗口永远初始化显示在屏幕中间的例子

package FileChooser;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class FileChooserDemo extends JPanel {

JFileChooser fileChooser;
JButton open;
JButton save;
JTextArea textArea;

public static void main(String[] args){
JFrame frame = new JFrame("FileChooser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new FileChooserDemo());
frame.pack();
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((int)(size.getWidth()-frame.getWidth())/2,
(int)(size.getHeight()-frame.getHeight())/2);
frame.setVisible(true);

}

FileChooserDemo(){

fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

open = new JButton("Open");
save = new JButton("Save");

this.setLayout(new BorderLayout());
JPanel buttonPane = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
buttonPane.add(open);
buttonPane.add(save);

textArea = new JTextArea(15,40);

this.add(new JScrollPane(textArea),BorderLayout.CENTER);
this.add(buttonPane,BorderLayout.SOUTH);

open.addActionListener(new ButtonAction());
save.addActionListener(new ButtonAction());
}

class ButtonAction implements ActionListener {
public void actionPerformed(ActionEvent e){
if(e.getSource() == open)
openFile();
if(e.getSource() == save)
saveFile();
}

public void openFile(){
int result = fileChooser.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
try{
File file = fileChooser.getSelectedFile();
BufferedReader input = new BufferedReader(new FileReader(file));

String line = input.readLine();
while(line != null){
textArea.append(line + "\n");
line = input.readLine();
}
input.close();

}catch(IOException ioe){
JOptionPane.showMessageDialog(null,ioe.toString());
}
}
}

public void saveFile(){
int result = fileChooser.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
try{
File file = fileChooser.getSelectedFile();
PrintWriter output = new PrintWriter(new FileWriter(file));

output.print(textArea.getText());
output.close();
}catch(IOException ioe){
JOptionPane.showMessageDialog(null, ioe.toString());
}
}
}
}

}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式