Results 1 to 15 of 15
Thread: problem with streams and swings
- 07-14-2009, 08:35 AM #1
Member
- Join Date
- Jun 2009
- Posts
- 30
- Rep Power
- 0
problem with streams and swings
hi to all .I think it may be silly doubt ,but i need to clarify this one.My question is
Is it possible to read swing components as streams[as input or output streams] ,like we can read text files and images as streams . If it is possible how this can be done .
please help me .Last edited by sandeepsai17; 07-14-2009 at 10:03 AM.
- 07-14-2009, 07:56 PM #2
Swing Components Are Serializable
Hi sandeepsai17. :D
Swing Components are serializable, so you can send them through object IO streams. I wrote a simple Java program to demonstrate this for you. ;) As long as the form.gui file exists, the GUI will be persistent, even if the application is terminated. Here's the code:
Note that the state of the button is saved. Also, the generate method is only called if the file doesn't exist.Java Code:package test; import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; public class Main extends JFrame implements ActionListener{ protected JPanel pnlGUI = null; protected JPanel load() throws Exception { BufferedInputStream bis = new BufferedInputStream(new FileInputStream("form.gui")); ObjectInputStream ois = new ObjectInputStream(bis); JPanel result = (JPanel) ois.readObject(); ois.close(); return result; } protected void save(JPanel panel) throws Exception { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("form.gui")); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(panel); oos.close(); } protected JPanel generate() { JPanel panel = new JPanel(new FlowLayout()); JButton button = new JButton("on"); button.addActionListener(this); panel.add(button); return panel; } public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source instanceof JButton) { JButton button = (JButton) source; if (button.getText().equals("on")) button.setText("off"); else button.setText("on"); } } public Main() { super("Test"); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { try { save(pnlGUI); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } System.exit(0); } }); buildGUI(); pack(); setVisible(true); } protected void buildGUI() { try { if ((new File("form.gui")).exists()) { pnlGUI = load(); } else { pnlGUI = generate(); } add(BorderLayout.CENTER, pnlGUI); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } public static void main(String[] args) { new Main(); } }
Hope this helps you. Good luck. ;)Eyes dwelling into the past are blind to what lies in the future. Step carefully.
- 07-15-2009, 06:01 AM #3
Member
- Join Date
- Jun 2009
- Posts
- 30
- Rep Power
- 0
thank you Tim . I got your point,i hope it will be a solution for my problem ,but not completed yet.If i get any problem i will come again.Thank you.
- 07-15-2009, 08:23 AM #4
Member
- Join Date
- Jun 2009
- Posts
- 30
- Rep Power
- 0
hi to all , i got another doubt. how to convert swing component as image file like form.jpeg. I am new to java .please don't get hesitation with my questions.
- 07-15-2009, 11:15 AM #5
Hey sandeepsai17. :D
I added a method to take a screen shot of the GUI and save it to a file when the frame closes. Here's the code again:
Ask if you have any more doubts. ;)Java Code:package test; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.io.*; import javax.imageio.*; import javax.swing.*; public class Main extends JFrame implements ActionListener{ protected JPanel pnlGUI = null; protected JPanel load() throws Exception { BufferedInputStream bis = new BufferedInputStream(new FileInputStream("form.gui")); ObjectInputStream ois = new ObjectInputStream(bis); JPanel result = (JPanel) ois.readObject(); ois.close(); return result; } protected void saveAsImage(File file) throws Exception { BufferedImage buffer = new BufferedImage(pnlGUI.getWidth(), pnlGUI.getHeight(), BufferedImage.TYPE_INT_ARGB); pnlGUI.print(buffer.getGraphics()); ImageIO.write(buffer, "png", file); } protected void save(JPanel panel) throws Exception { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("form.gui")); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(panel); oos.close(); } protected JPanel generate() { JPanel panel = new JPanel(new FlowLayout()); JButton button = new JButton("on"); button.addActionListener(this); panel.add(button); return panel; } public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source instanceof JButton) { JButton button = (JButton) source; if (button.getText().equals("on")) button.setText("off"); else button.setText("on"); } } public Main() { super("Test"); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { try { saveAsImage(new File("form.png")); save(pnlGUI); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } System.exit(0); } }); buildGUI(); pack(); setVisible(true); } protected void buildGUI() { try { if ((new File("form.gui")).exists()) { pnlGUI = load(); } else { pnlGUI = generate(); } add(BorderLayout.CENTER, pnlGUI); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } public static void main(String[] args) { new Main(); } }Eyes dwelling into the past are blind to what lies in the future. Step carefully.
- 07-15-2009, 11:59 AM #6
Member
- Join Date
- Jun 2009
- Posts
- 30
- Rep Power
- 0
Thank you Tim once again , i already did as you said saving swing to a file but actually what my doubt is [it is my mistake not correctly specifying problem]
i want to display swing components as screen shoots suppose when i click a button with out saving image to a file.Thanks for your help.
- 07-15-2009, 05:01 PM #7
Hey sandeepsai17.
I've changed it again. It takes screen shots of the GUI as you click the buttons, and adds them to the combo box. Please note that BufferedImage instances cannot be serialized. So the save() method will not work. Here's the code:
Hope this helps you. ;)Java Code:package test; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.io.*; import java.util.*; import javax.imageio.*; import javax.swing.*; public class Main extends JFrame implements ActionListener, ListCellRenderer { protected JPanel pnlGUI = null; protected JComboBox cmbScreenshots; protected JPanel load() throws Exception { BufferedInputStream bis = new BufferedInputStream(new FileInputStream("form.gui")); ObjectInputStream ois = new ObjectInputStream(bis); JPanel result = (JPanel) ois.readObject(); ois.close(); return result; } protected void saveAsImage(File file) throws Exception { BufferedImage buffer = new BufferedImage(pnlGUI.getWidth(), pnlGUI.getHeight(), BufferedImage.TYPE_INT_ARGB); pnlGUI.print(buffer.getGraphics()); ImageIO.write(buffer, "png", file); } protected BufferedImage getScreenshot() { BufferedImage buffer = new BufferedImage(pnlGUI.getWidth(), pnlGUI.getHeight(), BufferedImage.TYPE_INT_ARGB); pnlGUI.print(buffer.getGraphics()); return buffer; } protected void save(JPanel panel) throws Exception { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("form.gui")); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(panel); oos.close(); } protected JPanel generate(int count) { JPanel panel = new JPanel(new FlowLayout()); for (int i = 1; i <= count; i++) { JButton button = new JButton("on"); button.addActionListener(this); panel.add(button); } return panel; } public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source instanceof JButton) { JButton button = (JButton) source; if (button.getText().equals("on")) button.setText("off"); else button.setText("on"); (new Thread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (Exception e) { // ignore } ((DefaultComboBoxModel) cmbScreenshots.getModel()).addElement(getScreenshot()); } })).start(); } } class JImage extends JPanel { protected Image image = null; protected boolean selected = false; public JImage(Image image, boolean selected) { super(); this.image = image; this.selected = selected; } public void paint(Graphics g) { if (image != null) { g.drawImage(image, getWidth() / 2 - image.getWidth(null) / 2, getHeight() / 2 - image.getHeight(null) / 2, image.getWidth(null) , image.getHeight(null), null); if (selected) { g.setColor(new Color(SystemColor.textHighlight.getRed(), SystemColor.textHighlight.getGreen(), SystemColor.textHighlight.getBlue(), 50)); g.fillRect(0, 0, getWidth(), getHeight()); } } } public Dimension getPreferredSize() { return new Dimension(image.getWidth(null), image.getHeight(null)); } } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { return new JImage((Image) value, isSelected); } public Main() { super("Test"); setSize(400, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); buildGUI(); setVisible(true); } protected void buildGUI() { try { cmbScreenshots = new JComboBox(new DefaultComboBoxModel()); cmbScreenshots.setRenderer(this); pnlGUI = generate(3); getContentPane().setLayout(new BorderLayout(5, 5)); JPanel hold = new JPanel(new FlowLayout()); hold.add(pnlGUI); getContentPane().add(BorderLayout.CENTER, hold); getContentPane().add(BorderLayout.NORTH, cmbScreenshots); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } public static void main(String[] args) { new Main(); } }Eyes dwelling into the past are blind to what lies in the future. Step carefully.
- 07-16-2009, 06:10 AM #8
Member
- Join Date
- Jun 2009
- Posts
- 30
- Rep Power
- 0
thank u tim , actually this is my requirement ,but i am unable to understand is paint() and rePaint() methods in swings even when i read java documentation i am so confused with this two methods .I hope i am not following swing practice in correct way .Please help me ,by giving appropriate links or explanation.I am unable to understand this part of code .please help me.
thank you .Java Code:class JImage extends JPanel { protected Image image = null; protected boolean selected = false; public JImage(Image image, boolean selected) { super(); this.image = image; this.selected = selected; } public void paint(Graphics g) { if (image != null) { g.drawImage(image, getWidth() / 2 - image.getWidth(null) / 2, getHeight() / 2 - image.getHeight(null) / 2, image.getWidth(null) , image.getHeight(null), null); if (selected) { g.setColor(new Color(SystemColor.textHighlight.getRed(), SystemColor.textHighlight.getGreen(), SystemColor.textHighlight.getBlue(), 50)); g.fillRect(0, 0, getWidth(), getHeight()); } } }Last edited by sandeepsai17; 07-16-2009 at 07:41 AM.
- 07-16-2009, 11:35 AM #9
Hey sandeepsai17. :)
The paint() method for JComponent defines how the component looks. I'm overriding this method, for my own component, so that it draws an image. The repaint() method for Component, calls the repaint() method for the JComponent, which then tells the component to be redrawn. That is, the system will call my paint() method later. Also, note that JComponent is extended from Component. I'll give you the bouncing box example next. Please note that in this example, threading and double buffering was used. Also the Panel class was extended instead of the JPanel class, because the update() method is only called for heavy weight components. Swing components are light weight. I don't fully understand what the weight of a component is, so you might want to read that up. :) Here's the code:
Hope this code helps you, and opens a few new doors. ;)Java Code:package painting; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.swing.*; public class Main extends Panel implements Runnable { protected BufferedImage buffer; protected Rectangle box = new Rectangle(100, 50, 100, 100); protected Point velocity = new Point(4, 2); public Main() { super(); addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { if (getWidth() > 0 && getHeight() > 0) buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); } public void componentShown(ComponentEvent e) { if (getWidth() > 0 && getHeight() > 0) buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); } }); (new Thread(this)).start(); } public static void main(String[] args) { JFrame frmTest = new JFrame("Bouncing box"); frmTest.setSize(400, 300); frmTest.add(BorderLayout.CENTER, new Main()); frmTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmTest.setVisible(true); } public void paint(Graphics g) { g.drawImage(buffer, 0, 0, null); } protected void act() { if (box.x < 0 || box.x + box.width > getWidth()) velocity.x *= -1; if (box.y < 0 || box.y + box.height > getHeight()) velocity.y *= -1; box.translate(velocity.x, velocity.y); } protected void draw() { if (buffer != null) { Graphics graphics = buffer.getGraphics(); graphics.setColor(new Color(255, 255, 255, 50)); graphics.fillRect(0, 0, getWidth(), getHeight()); graphics.setColor(Color.BLACK); graphics.fillRect(box.x, box.y, box.width, box.height); } } // I'm overriding update so that I can draw on my buffer first. This stops the flickering. public void update(Graphics g) { draw(); paint(g); // now I'm calling paint() } public void run() { while (true) { try { Thread.sleep(10); } catch (Exception e) { // ignore } act(); repaint(); // this method will call update() } } }Eyes dwelling into the past are blind to what lies in the future. Step carefully.
- 07-16-2009, 01:24 PM #10
Member
- Join Date
- Jun 2009
- Posts
- 30
- Rep Power
- 0
thank you Tim.I understand Paint and RePaint methods. Actually what i am trying to do is generating print Preview for swings as we needed like zooming ,changing sizes etc....I want to do this on my own ,can you say what is the best way to do this.
- 07-16-2009, 07:45 PM #11
Hi sandeepsai17. ;)
I would store the screen shots in a vector or some linear data structure. Then I would build a preview GUI with toolbars that include zoom, pan, print and other commands. Maybe, you could use your own icons. Then, I would have a vertical scrollbar to the right, so that the user can scroll through the screens. I would draw them in frames when the screen shot fit's in the window, with a dark gray background. Try to mimic MS Word or Open Office's print view. It's always good practice to give the user what he or she expects. :D
Don't know if that answer your question. :p If you have more questions, just ask. :)Eyes dwelling into the past are blind to what lies in the future. Step carefully.
- 07-17-2009, 06:14 AM #12
Member
- Join Date
- Jun 2009
- Posts
- 30
- Rep Power
- 0
thank u tim ,you did almost every thing for me.Because i am trying to create on my own it is taking long time for me.when i got some doubt i am posting in this forum only and searching on google and java api, hey you observe one thing two people are talking in this forum you and me just like chatting. I hope they are busy . I respect you.sorry for personal chatting it may waste your time.
Thank you very much .This thread is not over yet .Please stay with me .
- 07-17-2009, 09:39 AM #13
Hey sandeepsai17. :D
I don't consider this as a waste of time. I've learned as well. :D
I'm busy with a project too. It's very big for me, so I've split it into many small pieces. I'm now busy with a "network file sharing service". I like to reinvent the wheel, mainly because I don't like/understand "their" wheel.
I'll stay here. ;)Last edited by tim; 07-17-2009 at 09:44 AM.
Eyes dwelling into the past are blind to what lies in the future. Step carefully.
- 07-20-2009, 12:18 PM #14
Member
- Join Date
- Jun 2009
- Posts
- 30
- Rep Power
- 0
hi Tim , I am back again with new problem ,this time my problem with printing, I have my paper with my required size on printer and i want to print the text or any thing ,what ever it may be at my required position say at middle or left side etc.. some thing like that . I tried it with implementing Pagable and printable interfaces i suceed to print it in random order .But i am unable to specify starting line,starting position and filling it with borders like .Please help me how to do this.
- 07-21-2009, 06:23 PM #15
Hi sandeepsai17. ;)
I've worked on a report printing component for my project. I managed to beef up the resolution from around 72 dpi to 150 dpi. I stopped at 150 dpi, because my solution is a bit (very) heavy on the JVM's memory. :rolleyes: But, anyways. I stripped it down, providing you with its wire frame. Here's the code of an example. It will print 3 pages, each with an extra colored line across the page:
You can drop the buffering if you want to. My studies have begun today. So I'm gonna have less free time. :p Also, here's a link to a site I used to learn how to print stuff in Java. And take a look at Java Tutorial. Very cool stuff. ;)Java Code:// WARNING: VERY HEAVY ON MEMORY. RUN WITH // -Xms150m -Xmx300m package printing; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.print.*; import java.util.*; import javax.print.attribute.*; import javax.print.attribute.standard.*; public class Main implements Printable { public static final double PIXELS_PER_CENTIMETER = 28.346456692913385826771653543307d; public static final double RESOLUTION_CROSS = 150d; public static final double RESOLUTION_FEED = 150d; private double leftMargin = PIXELS_PER_CENTIMETER; private double rightMargin = PIXELS_PER_CENTIMETER; private double topMargin = PIXELS_PER_CENTIMETER; private double bottomMargin = PIXELS_PER_CENTIMETER; public Main() { try { print(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new Main(); } public void setTopMargin(double topMargin) { this.topMargin = topMargin; } public void setRightMargin(double rightMargin) { this.rightMargin = rightMargin; } public void setLeftMargin(double leftMargin) { this.leftMargin = leftMargin; } public void setBottomMargin(double bottomMargin) { this.bottomMargin = bottomMargin; } public double getRightMargin() { return rightMargin; } public double getTopMargin() { return topMargin; } public double getLeftMargin() { return leftMargin; } public double getBottomMargin() { return bottomMargin; } // Dummy code protected final int numberOfPages = 3; // private boolean generate(Graphics graphics, int pageIndex, int left, int top, int width, int height) { // to your painting here on the graphics object, within the bounds: // left, top, width and height // return true if pageIndex is valid, false if not // this method can be called multiple times for the same page // PAINT HERE if (pageIndex >= 0 && pageIndex < numberOfPages) { // draw n lines from the top-left corner to the bottom right corner int n = pageIndex + 1; final int skip = 10; for (int i = 1; i <= n; i++) { Point topLeft = new Point(left + i * skip, top), bottomRight = new Point(left + width + i * skip, top + height); switch (i) { case 1: graphics.setColor(Color.RED); break; case 2: graphics.setColor(Color.GREEN); break; case 3: graphics.setColor(Color.BLUE); break; } graphics.drawLine(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y); } return true; } else return false; } public BufferedImage getPageImage(int pageIndex, int width, int height) { BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics graphics = result.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, width, height); if (generate(graphics, pageIndex, 0, 0, width, height)) return result; else return null; } public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { int left = (int) pageFormat.getImageableX(), top = (int) pageFormat.getImageableY(), width = (int) pageFormat.getImageableWidth(), height = (int) pageFormat.getImageableHeight(); PrinterJob printerJob = getPrinterJob(); int pageWidth = (int) (printerJob.defaultPage().getPaper().getWidth() / 72d * RESOLUTION_CROSS), pageHeight = (int) (printerJob.defaultPage().getPaper().getHeight() / 72d * RESOLUTION_FEED); BufferedImage next = getPageImage(pageIndex, pageWidth, pageHeight); boolean hasPage = next != null; graphics.dispose(); if (hasPage) { graphics.drawImage(next, left, top, width, height, null); return Printable.PAGE_EXISTS; } else return Printable.NO_SUCH_PAGE; } protected PrinterJob getPrinterJob() { PrinterJob printerJob = PrinterJob.getPrinterJob(); printerJob.setPrintable(this); return printerJob; } public void print() throws Exception { PrinterJob printerJob = getPrinterJob(); if (printerJob.printDialog()) { printerJob.print(); } } }
Hope this helps sandeepsai17, good luck! :DEyes dwelling into the past are blind to what lies in the future. Step carefully.
Similar Threads
-
jdbc with swings
By raghu9198 in forum New To JavaReplies: 3Last Post: 06-24-2009, 10:42 PM -
interface in swings
By r.srimathi in forum AWT / SwingReplies: 4Last Post: 01-29-2009, 08:44 AM -
awt and swings
By masa in forum AWT / SwingReplies: 2Last Post: 11-24-2008, 07:09 AM -
Problem With Streams
By mm2236 in forum Advanced JavaReplies: 2Last Post: 09-23-2008, 01:01 PM -
java swings
By emperoraj in forum AWT / SwingReplies: 0Last Post: 03-26-2008, 11:50 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks