Java JFrame Büyüklüğünün Ve Koordinatlarının Restore Edilmesi
26-09-2014
Java GUI uygulamasında, Frame'in büyüklüğünün ve ekranda gösterildiği lokasyonun, uygulama kapatıldıktan sonra, aynı değerlere sahip olması için aşağıdaki kodları kullanabiliriz:
FileOp Class
import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; public class Main extends JFrame { private Rectangle bounds; public Main() { setTitle("Continue From Last Location"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(new BorderLayout()); try { Rectangle dimension = (Rectangle) FileOp.readObject(FileOp.tempDirectory + "lastLocation.tmp"); if (dimension != null) { setSize(dimension.getSize()); setLocation((int) dimension.getX(), (int) dimension.getY()); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } setCloseListener(); setVisible(true); } /* * When JFrame is closed, save last location and dimension to a file */ private void setCloseListener() { this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { //this method returns Rectangle object which contains x, y coordinate values and Dimension object bounds = getBounds(); try { FileOp.writeObject(bounds, FileOp.tempDirectory + "lastLocation.tmp"); } catch (IOException e1) { e1.printStackTrace(); } } }); } public static void main(String[] args) { new Main(); } }
FileOp Class
/* * Write and Read File Operations */ public class FileOp { public static final String tempDirectory = System.getProperty("java.io.tmpdir"); public static void writeObject(Object content, String filePath) throws IOException { FileOutputStream fos = new FileOutputStream(filePath); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(content); oos.close(); } public static Object readObject(String filePath) throws IOException, ClassNotFoundException { File file = new File(filePath); if (file.exists()) { FileInputStream fis = new FileInputStream(filePath); ObjectInputStream ois = new ObjectInputStream(fis); Object content = ois.readObject(); ois.close(); return content; } else { return null; } } }