I have a question regarding accessing GUI elements. For example having a simple GUI program on Java, how can I read and save the Swing GUI elements hierarchy on a tree (ex. including main window, frames, button, textfield, combobox etc.).
Swing applications are already organized in trees. The JFrame is the root, children can be visited by:
Component[] components1 = mFrame.getContentPane().getComponents();
Every components has sub-components that you can get by:
// Assuming component is a container
((Container)component).getComponents();
Saving these elements into a file is an easy operation. Here is a good article to get you strated.
EDIT The beauty of streams is that you can use a file just as you would use a socket :) Thus turning ComponentSerializer component to serialize into a file instead of a socket requires 0 changes :)
Say your have a JFrame you want to save/read to/from a file, you do the following:
OutputStream output = new FileOutputStream("FileName.bin");
JFrame myFrame = new JFrame();
ComponentSerializer serializer = new ComponentSerializer();
serializer.write(myFrame, output);
// Reading from file
InputStream in = new FileInputStream("FileName.bin");
ComponentSerializer serializer = new ComponentSerializer();
JFrame myFrame = (JFrame) serializer.read(in);
myFrame.setVisible(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With