Serializing a JPanel

Hi,
I am trying to serialize a JPanel and then open it again. My JPanel (called rightPanel) contains a JButton, which has some text set to "xyz". Would I have to serialize the JPanel and JButton separately? Or if I serialize the JPanel, would that take care of the JButton too?
At the moment my code is like this:
JFileChooser myFileChooser = new JFileChooser ();
myFileChooser.showSaveDialog(MyFrame.this);
File myFile = myFileChooser.getSelectedFile();
try{
FileOutputStream out = new FileOutputStream(myFile);
ObjectOutputStream s = new ObjectOutputStream(out);
s.writeObject(rightPanel);
s.flush
} catch (IOException e) {};
When I execute my Save, a file is saved onto my system. I do not know if the saved file contains my rightPanel.
When I try to open up the file (by doing a readObject), nothing happens. What am I doing wrong?
Any help would be much appreciated.
Thanks.
AU

You make some very good points there. I do totally agree with you that serializing Swing components is discouraged.
But you see the reason I am trying to serialize my JPanel is because of this. Say the components on my JPanel will be determined on-the-fly by clicking on buttons on my JToolbar. So that means on one occasion a user might add to my JPanel a JButton, followed by 20 JLabels, all of different sizes. On the next occasion my JPanel might contain a 100 JButtons, a few jpeg images, and a textbox. Are you suggesting I should use something like a Vector to store everything that is added to my JPanel, and that everytime I add an item to it, I also add it to the Vector...and then when I want to Save my JPanel, I traverse through my Vector, serializing the attributes of every object in my Vector.
That makes more code for me!!!
AU

Similar Messages

  • How to Click on Shape After Rotating it?

    In trying to answer a question on another forum ([java-forums question|http://www.java-forums.org/awt-swing/20517-how-select-shape-object-after-rotation.html]) on how to click on a shape after it has been rotated, I created an SSCCE (actually a little too big for one, sorry), and got a solution by re-rotating the shape in the mouse listener, but is this a decent solution? Are there better solutions? My so-called SSCCE:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.*;
    public class RotateShape {
       private static final int PANEL_WIDTH = 500;
       private static final int SHAPE_WIDTH = 100;
       private static final Dimension MAIN_SIZE =
          new Dimension(PANEL_WIDTH, PANEL_WIDTH);
       private static final int SLIDER_MIN = -180;
       private static final int SIDER_MAX = 180;
       private static final int MAJOR_TICK = 30;
       private static final int MINOR_TICK = 15;
       private List<MyShape> myShapeList = new ArrayList<MyShape>();
       private JPanel mainPanel = new JPanel();
       private JPanel drawingPanel = createDrawingPanel();
       private AffineTransform transform = new AffineTransform();
       private JSlider rotationSlider;
       public RotateShape() {
          mainPanel.setLayout(new BorderLayout());
          mainPanel.add(drawingPanel, BorderLayout.CENTER);
          mainPanel.add(createTransformPanel(), BorderLayout.SOUTH);
       private JPanel createTransformPanel() {
          rotationSlider = new JSlider(SLIDER_MIN, SIDER_MAX, 0);
          rotationSlider.setMajorTickSpacing(MAJOR_TICK);
          rotationSlider.setMinorTickSpacing(MINOR_TICK);
          rotationSlider.setPaintLabels(true);
          rotationSlider.setPaintTicks(true);
          rotationSlider.setPaintTrack(true);
          rotationSlider.setSnapToTicks(true);
          rotationSlider.addChangeListener(new SliderListener());
          JPanel transformingPanel = new JPanel(new BorderLayout());
          transformingPanel.setBorder(BorderFactory.createEtchedBorder());
          transformingPanel.add(rotationSlider);
          return transformingPanel;
       @SuppressWarnings("serial")
       private JPanel createDrawingPanel() {
          if (drawingPanel != null) {
             return drawingPanel;
          drawingPanel = new JPanel() {
             @Override
             protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                myPaint(g);
          int leftUpperCenter = PANEL_WIDTH / 4;
          int x = leftUpperCenter - SHAPE_WIDTH / 2;
          int y = x;
          MyShape rect = new MyShape(
                new Rectangle2D.Double(x, y, SHAPE_WIDTH, SHAPE_WIDTH));
          MyShape circle = new MyShape(
                new Ellipse2D.Double(PANEL_WIDTH - x - SHAPE_WIDTH,
                      y, SHAPE_WIDTH, SHAPE_WIDTH));
          MyShape roundedRect = new MyShape(new RoundRectangle2D.Double(x,
                PANEL_WIDTH - y - SHAPE_WIDTH, SHAPE_WIDTH, SHAPE_WIDTH, 30, 30));
          myShapeList.add(rect);
          myShapeList.add(circle);
          myShapeList.add(roundedRect);
          drawingPanel.setPreferredSize(MAIN_SIZE);
          drawingPanel.addMouseListener(new MouseAdapter() {
             public void mousePressed(MouseEvent e) {
                myMousePressed(e);
          return drawingPanel;
       private void myMousePressed(MouseEvent e) {
          for (MyShape myShape : myShapeList) {
             if (myShape.contains(e.getPoint(), transform)) {
                // toggle fill if shape is clicked
                myShape.setFill(!myShape.isFilled());
          drawingPanel.repaint();
       private void myPaint(Graphics g) {
          Graphics2D g2 = (Graphics2D) g;
          g2.setStroke(new BasicStroke(3));
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
          AffineTransform oldTransform = g2.getTransform();
          if (transform != null) {
             g2.setTransform(transform);
          g2.setColor(Color.red);
          for (MyShape myShape : myShapeList) {
             if (myShape.isFilled()) {
                myShape.fill(g2);
          g2.setColor(Color.blue);
          for (MyShape myShape : myShapeList) {
             myShape.draw(g2);
          g2.setTransform(oldTransform);
       public JComponent getPanel() {
          return mainPanel;
       private class SliderListener implements ChangeListener {
          public void stateChanged(ChangeEvent e) {
             double theta = Math.PI * rotationSlider.getValue() / 180;
             double center = (double) PANEL_WIDTH / 2;
             transform = AffineTransform.getRotateInstance(theta, center, center);
             drawingPanel.repaint();
       private static void createAndShowGUI() {
          JFrame frame = new JFrame("RotateShape Application");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new RotateShape().getPanel());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       public static void main(String[] args) {
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGUI();
    * Holds a Shape and a boolean filled that tells if Shape is to be filled or not
    class MyShape {
       private Shape shape;
       private boolean filled = false;
       public MyShape(Shape shape) {
          this.shape = shape;
       public boolean isFilled() {
          return filled;
       public void setFill(boolean fill) {
          this.filled = fill;
       public Shape getShape() {
          return shape;
       public void draw(Graphics2D g2) {
          g2.draw(shape);
       public void fill(Graphics2D g2) {
          g2.fill(shape);
       public boolean contains(Point2D p) {
          return shape.contains(p);
       public boolean contains(Point2D p, AffineTransform at) {
          Shape s = at.createTransformedShape(shape);
          return s.contains(p);
    }Many thanks!
    edit: code change -- MyShape has its own draw, fill, contains(point2d), and contains({Point2D, AffineTransform) methods.
    Edited by: Encephalopathic on Aug 13, 2009 5:47 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

        public boolean contains(Point2D p, AffineTransform at) {
         try {
             return shape.contains(at.inverseTransform(p, null));
         } catch (NoninvertibleTransformException e) {
             e.printStackTrace();
             return false;
         // Shape s = at.createTransformedShape(shape);
         // return s.contains(p);
        }Piet
    Edited by: pietblok on 20-aug-2009 6:51
    Changed return value on exception

  • Xml Serializing a class that extends JPanel

    Alright I am getting an Exception saying java.
    java.lang.reflect.InvocationTargetException
    Continuing ...
    java.lang.Exception: XMLEncoder: discarding statement XMLEncoder.writeObject(JpanelScreen);
    Continuing ...
    is anyone familiar with this... It ocurrs when I try to Serialize my class object that extends JPanel...

    any examples of how to do this?
    try {
    java.beans.XMLEncoder out = new java.beans.XMLEncoder( new BufferedOutputStream( new java.io.FileOutputStream(getFilename())));
    out.writeObject(Screen);
    out.close();
    }catch (Exception exc) {System.err.println(exc.getMessage());}

  • Problem de-serializing JPanel with null LayoutManager using XMLDecode

    Hi,
    I'm using Java 1.4.1_01 XMLEncoder/XMLDecoder to serialize JPanel Objects. This works fine if standard Java LayoutManagers (like BorderLayout, ...) are assigned to the JPanels.
    Now I'm trying to encode/decode the same JPanel objects using the null LayoutManager, placing the components on the JPanel using the setBounds(Rectangle) method.
    The XML file generated by XMLEncode looks like this :
    <?xml version="1.0" encoding="UTF-8"?>
    <java version="1.4.1_01" class="java.beans.XMLDecoder">
    <object class="javax.swing.JPanel">
    <void method="add">
    <object class="javax.swing.JLabel">
    <void property="bounds">
    <object class="java.awt.Rectangle">
    <int>0</int>
    <int>40</int>
    <int>56</int>
    <int>16</int>
    </object>
    </void>
    which looks fine to me.
    Trying to read this with XMLDecode does not place the components on the JPanel, i.e. the panel remains empty.
    After running the XMLDecoder on the XML file and looking at the readObject() method's result
    [0]= JLabel (id=79)
         _bounds= Rectangle  (id=213)
              height= 16
              width= 56
              x= 0
              y= 40
         accessibleContext= null
         accessibleContext= null
         accessibleIcon= null
         actionMap= null
         alignmentX= Float (id=214)
              value= 0.0
         alignmentY= null
    I noticed that the JLabel's bounds are named '_bounds' here ... don't know if that's a problem, but it looks a bit strange ...
    Anyway, thanks for any hints on how to get XMLEncoder/XMLDecoder to work with a null LayoutManager.
    Ingo

    Did you ever receive an answer regarding this?

  • Serializing an extension of JPanel

    The title says it all :p
    Basically i have a class called Palette which implements serializable.
    When i try to write it to an file with an ObjectOutputStream like this:
    saveButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    File selectedFile;
                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.addChoosableFileFilter(new PaletteFileFilter());
                    int returnValue = fileChooser.showSaveDialog(null);
                    if (returnValue == JFileChooser.APPROVE_OPTION) {
                        selectedFile = fileChooser.getSelectedFile();
                        System.out.println(selectedFile.getName());
                        try{
                            ObjectOutputStream objectOut = new ObjectOutputStream(
                                    new FileOutputStream(selectedFile.getName() + ".pppp"));
                            objectOut.writeObject(this);
                            objectOut.close();
                            JOptionPane.showMessageDialog(null, "Save Successful!");
                        } catch(Exception ex){
                            System.out.println("hmm");
                            ex.printStackTrace();
            });it gives me this error at runtime:
    java.io.NotSerializableException: Palette$2What else does a class need to do apart from implementing serializable to be serializable?
    please help!
    thanks

    ok, its pretty massive:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    public class Palette extends JPanel implements Serializable{
        Color current;//current colour
        ColorButton selected;
        Color secondary;
        JButton addButton, removeButton, saveButton;
        JPanel gridPanel;
        SelectionBox sb;
        public Palette(){
            current = Color.BLACK;
            secondary = Color.WHITE;
            gridPanel = new JPanel();
            gridPanel.setLayout(new GridLayout(2, 10));
            this.setLayout(null);
            gridPanel.add(new ColorButton(Color.BLACK, this));
            gridPanel.add(new ColorButton(Color.WHITE, this));
            gridPanel.add(new ColorButton(Color.GRAY, this));
            gridPanel.add(new ColorButton(Color.YELLOW, this));
            gridPanel.add(new ColorButton(Color.BLUE, this));
            gridPanel.add(new ColorButton(Color.RED, this));
            gridPanel.add(new ColorButton(Color.GREEN, this));
            gridPanel.add(new ColorButton(Color.MAGENTA, this));
            addButton = new JButton("Add");
            addButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    Color c = JColorChooser.showDialog(Palette.this, "Choose Color", Color.white);
                    ColorButton p = new ColorButton(c, Palette.this);
                    Palette.this.addNewColor(p);
                    repaint();
                    gridPanel.repaint();
                    gridPanel.validate();
                    resizeGrid();
            saveButton = new JButton("Save");
            saveButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    File selectedFile;
                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.addChoosableFileFilter(new PaletteFileFilter());
                    int returnValue = fileChooser.showSaveDialog(null);
                    if (returnValue == JFileChooser.APPROVE_OPTION) {
                        selectedFile = fileChooser.getSelectedFile();
                        System.out.println(selectedFile.getName());
                        try{
                            ObjectOutputStream objectOut = new ObjectOutputStream(
                                    new FileOutputStream(selectedFile.getName() + ".pppp"));
                            objectOut.writeObject(this);
                            objectOut.close();
                            JOptionPane.showMessageDialog(null, "Save Successful!");
                        } catch(Exception ex){
                            System.out.println("hmm");
                            ex.printStackTrace();
            int i = gridPanel.getComponentCount();
            addButton.setContentAreaFilled(false);
            saveButton.setContentAreaFilled(false);
            removeButton = new JButton("Remove");
            removeButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    if(selected != null){
                        gridPanel.remove(selected);
                        resizeGrid();
                        gridPanel.repaint();
                        gridPanel.validate();
                        repaint();
            removeButton.setContentAreaFilled(false);
            resizeGrid();
            sb = new SelectionBox();
            sb.setPrimary(Color.BLACK);
            sb.setSecondary(Color.WHITE);
            sb.setSize(50, 50);
            sb.setLocation(5, 5);
            gridPanel.setLocation(60, 5);
            addButton.setSize(80, 15);
            addButton.setLocation(60, 35);
            removeButton.setSize(100, 15);
            removeButton.setLocation(140, 35);
            saveButton.setSize(100, 15);
            saveButton.setLocation(240, 35);
            add(sb);
            add(gridPanel);
            add(addButton);
            add(removeButton);
            add(saveButton);
        public void setCurrentColor(Color c){
            current = c;
            sb.setPrimary(c);
        public Color getCurrentColor(){
            return current;
        public void setSecondColor(Color c){
            secondary = c;
            sb.setSecondary(c);
        public Color getSecondColor(){
            return secondary;
        public void addNewColor(ColorButton cb){
            gridPanel.add(cb);
            gridPanel.repaint();
            gridPanel.validate();
            resizeGrid();
            repaint();
        public void setSelectedColor(ColorButton cb){
            selected = cb;
        public ColorButton getSelectedColor(){
            return selected;
        public void resizeGrid(){
            int i = gridPanel.getComponentCount();
            if(i%2 == 0) {
                gridPanel.setSize((i/2)*15, 30);
            } else{
                gridPanel.setSize(((i+1)/2)*15, 30);
        public void clearSelection(){
            if(selected != null){
                selected.setBackground(Color.WHITE);
    }

  • How to Serialize a JPanel which is inside a JApplet

    Hi..
    I have a JApplet where i have a JPanel which contains some JLabels and JTextFields,now i have to Serialize that full Panel so that i can retrived it later on with the labels and textfields placed in the same order,for that i tried serializing the full panel on to a file but it is giving me NotSerializeException,i dont know how to tackel it..
    public SaveTemplate(JPanel com) {
    try {
    ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("Temp1.temp"));
    os.writeObject(com);
    catch(Exception e) {
    e.printStackTrace();
    This is the code..plz help me with that..

    Actually its forming a Template which client will generate and that has to saved on the serverside..So what i thought that once when the client has designed a template,i can save the full template which is a panel into a file and later on when he want to open the template i just have to read the file and create an object of JPanel and add to the frame,so i dont need to apply much effort for that...But now serialization in Applet is giving problem.

  • Problem with JPanel removeAll()

    I have a JPanel which when the method newGame is called should remove all buttons from its child JPanel buttons. When newGame is callled by the JFrame containing this JPanel it does not work, yet other testing shows my code does what it should. Can anyone explain how to fix this?
    import java.awt.GridLayout;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    @SuppressWarnings("serial")
    public class MinePanel extends JPanel {
         private JLabel label;
         public JPanel buttons;
         private MineField mineField;
         private int[][] field;
         private int moves;
         private ButtonAbstract buttonArray[][]=new ButtonAbstract[MineField.ROWS][MineField.COLS];
         public MinePanel() {
              initMineField();
              initLabel();
              initButtons();
         private void initLabel(){
         private void initMineField(){
         private void initButtons(){
              buttons=new JPanel();
              buttons.setLayout(new GridLayout(MineField.ROWS, MineField.COLS));
              //Create MineField
              for(int x=0; x<MineField.ROWS; x++){
                   for(int y=0; y<MineField.COLS; y++){
                        //buttons.remove(buttonArray[x][y]);
                        if(field[x][y]==-1)
                             buttonArray[x][y]=new ButtonMine(this,x,y);
                        else
                             buttonArray[x][y]=new ButtonSpace(this,x,y,field[x][y]);
                        buttons.add(buttonArray[x][y]);
              add(buttons);
         private String labelText(){
         public void buttonPressed(int row, int col) {
              moves++;
              label.setText(labelText());
              mineField.clearPosition(row, col);
              uncoverAll();
              repaint();
              if(mineField.hasLost()){
                   mineField.clearAll();
                   uncoverAll();
                   JOptionPane.showMessageDialog(this, "You've been nuked!");
              else if (mineField.hasWon()){
                   mineField.clearAll();
                   uncoverAll();
                   JOptionPane.showMessageDialog(this, "Congratulations!\nYou've Won!");
         public void uncoverAll(){
              boolean [][] c=mineField.getClearfield();
              for(int x=0; x<MineField.ROWS;  x++){
                   for(int y=0; y<MineField.COLS; y++){
                        if(c[x][y])
                             buttonArray[x][y].showValue();
         public void newGame() {
              System.out.println("newGame() has been called.");
              buttons.removeAll();
              repaint();
              validate();
              initMineField();
              initButtons();
              moves=0;
              label.setText(this.labelText());
    }

    First off, you should ask SWING related question (surprise, surprise) in the [SWING forum|http://forums.sun.com/forum.jspa?forumID=57].
    nhwalker89 wrote:
    public void newGame() {
         buttons.removeAll();
         repaint();
         validate();
    Try public void newGame() {
         buttons.removeAll();
         revalidate();
    }instead. If this does not help, please explain in which way "it does not work".

  • Why won't JPanel show up in an external JFrame?

    My code generates a graph and displays it in a JPanel.
    If the class extends JFrame, the output looks exactly as it should. The problem is that I need to extend it as a JPanel so that I can imbed it in another GUI. When I modify the code so that it is a JPanel, the graph does not show up at all (except a tiny little smudge).
    What am I missing? Here is a trimmed down version:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    * @author Rob Kallman <[email protected]>
    public class GraphSSCCE extends JPanel {
         protected JPanel mainPanel;
         protected JPanel graphPanel;
         protected final int FRAME_PANEL_WIDTH = 950;
         protected final int FRAME_PANEL_HEIGHT = 400;     
         protected final int GRAPH_PANEL_WIDTH = 950;
         protected final int GRAPH_PANEL_HEIGHT = 400;
         protected final int NODE_COUNT = 3;
         protected final int node_d = 30;
         protected int centerX = GRAPH_PANEL_WIDTH/2;
         protected int centerY = GRAPH_PANEL_HEIGHT/2;
         protected java.util.List<Node> nodes = new ArrayList<Node>(NODE_COUNT);
         public GraphSSCCE() {
              //super("Graph Redux");
              this.setSize(FRAME_PANEL_WIDTH,FRAME_PANEL_HEIGHT);
              //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              mainPanel = new Graph();
              this.setBackground(Color.WHITE);
              this.add(mainPanel);
         public static void main(String args[]) {
              JFrame frame = new JFrame("Graph Test");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              GraphSSCCE gr = new GraphSSCCE();
              frame.setSize(gr.getSize());
              frame.add(gr);
              frame.setVisible(true);
    @SuppressWarnings("serial")
    class Graph extends JPanel {
         public Graph() {
              super();
              graphPanel = new JPanel();
              graphPanel.setBackground(Color.WHITE);
              graphPanel.setSize(GRAPH_PANEL_WIDTH, GRAPH_PANEL_HEIGHT);
              repaint();
         public void paint(Graphics g) {
              super.paint(g);
              int graphW = graphPanel.getWidth() - 100;
              int graphH = graphPanel.getHeight() - 100;
              //Draw Root node
              Node root = new Node(0, (graphPanel.getWidth() - 100)/4, graphH/2 + 20, node_d);
              g.setColor(Color.BLACK);
              g.fillOval(root.x-2, root.y-2, root.d + 4, root.d + 4);
              g.setColor(Color.RED);
              g.fillOval(root.x, root.y, root.d , root.d);
              //Draw site nodes
              for(int i = 0; i < NODE_COUNT; i++) {
                   double nc = NODE_COUNT;
                   double frac = i/(nc-1);
                   Node node = new Node(i, 3*(graphW)/4, (int)(frac * graphH) + 20 + (int)frac, node_d);
                   nodes.add(i, node);  // An ArrayList that contains all of the Node objects.
              // Populate network with edges from root to site     
                   for(Node noodle : nodes) {
                        g.setColor(Color.BLACK);
                        g.drawLine(root.x + root.d/2, root.y + root.d/2, noodle.x + noodle.d/2, noodle.y + noodle.d/2);
                        g.setColor(Color.BLACK);
                        g.fillOval(noodle.x - 2, noodle.y - 2, noodle.d + 4, noodle.d + 4);
                        g.setColor(Color.RED);
                        g.fillOval(noodle.x, noodle.y, noodle.d, noodle.d);
                   g.setColor(Color.BLACK);
                   g.fillOval(root.x - 2, root.y - 2, root.d + 4, root.d + 4);
                   g.setColor(Color.RED);  // Root
                   g.fillOval(root.x, root.y, root.d, root.d);
    class Node {
         protected int d;
         protected int x;
         protected int y;
         protected int node_id;
         public Node(int id, int x, int y, int d) {
              this.node_id = id;
              this.d = d;
              this.x = x;
              this.y = y;
    }

    Welcome to the Sun forums.
    >
    What am I missing? ...>That code was doing some odd things. Once I'd trimmed it down far enough to get it working, I'd made a number of undocumented changes. Have a look over this, and see if it get you back on track.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    * @author Rob Kallman <[email protected]>
    public class GraphSSCCE extends JPanel {
         public static void main(String args[]) {
              JFrame frame = new JFrame("Graph Test");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Graph gr = new Graph();
              JPanel mainPanel = new JPanel(new BorderLayout());
              mainPanel.add(gr, BorderLayout.CENTER);
              frame.setContentPane(mainPanel);
              frame.pack();
              frame.setSize(gr.getSize());
              frame.setVisible(true);
    @SuppressWarnings("serial")
    class Graph extends JPanel {
         protected final int FRAME_PANEL_WIDTH = 950;
         protected final int FRAME_PANEL_HEIGHT = 400;
         protected final int GRAPH_PANEL_WIDTH = 950;
         protected final int GRAPH_PANEL_HEIGHT = 400;
         protected final int NODE_COUNT = 3;
         protected final int node_d = 30;
         protected int centerX = GRAPH_PANEL_WIDTH/2;
         protected int centerY = GRAPH_PANEL_HEIGHT/2;
         protected java.util.List<Node> nodes = new ArrayList<Node>(NODE_COUNT);
         public Graph() {
              super();
              setBackground(Color.WHITE);
              repaint();
         public Dimension getPreferredSize() {
              return new Dimension(GRAPH_PANEL_WIDTH,GRAPH_PANEL_HEIGHT);
         /** Do not override paint() in a Swing component! */
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.setColor(getBackground());
              g.fillRect(0,0,getWidth(),getHeight());
              int graphW = getWidth() - 100;
              int graphH = getHeight() - 100;
              //Draw Root node
              Node root = new Node(0, (getWidth() - 100)/4, graphH/2 + 20, node_d);
              g.setColor(Color.BLACK);
              g.fillOval(root.x-2, root.y-2, root.d + 4, root.d + 4);
              g.setColor(Color.RED);
              g.fillOval(root.x, root.y, root.d , root.d);
              //Draw site nodes
              for(int i = 0; i < NODE_COUNT; i++) {
                   double nc = NODE_COUNT;
                   double frac = i/(nc-1);
                   Node node = new Node(i, 3*(graphW)/4, (int)(frac * graphH) + 20 + (int)frac, node_d);
                   nodes.add(i, node);  // An ArrayList that contains all of the Node objects.
              // Populate network with edges from root to site
                   for(Node noodle : nodes) {
                        g.setColor(Color.BLACK);
                        g.drawLine(root.x + root.d/2, root.y + root.d/2, noodle.x + noodle.d/2, noodle.y + noodle.d/2);
                        g.setColor(Color.BLACK);
                        g.fillOval(noodle.x - 2, noodle.y - 2, noodle.d + 4, noodle.d + 4);
                        g.setColor(Color.RED);
                        g.fillOval(noodle.x, noodle.y, noodle.d, noodle.d);
                   g.setColor(Color.BLACK);
                   g.fillOval(root.x - 2, root.y - 2, root.d + 4, root.d + 4);
                   g.setColor(Color.RED);  // Root
                   g.fillOval(root.x, root.y, root.d, root.d);
    class Node {
         protected int d;
         protected int x;
         protected int y;
         protected int node_id;
         public Node(int id, int x, int y, int d) {
              this.node_id = id;
              this.d = d;
              this.x = x;
              this.y = y;
    }

  • JTable in JPanel cut off

    I'm trying to put a JTable with several elements in a JPanel and it is getting cut off. I have tried extending the gridbagconstraints with ipady but no luck.
    public class PumpMonitor extends JPanel
    JTable Table1;
    PumpMonitor()
    Table1Model dm = new Table1Model();
    Table1 = new JTable( dm ) ;
    GridBagLayout gridBagLayout3 = new GridBagLayout();
    gridBagLayout3.rowHeights[0] = 300;
    Dimension size = new Dimension(300,400);
    this.setMinimumSize(size);
    this.setVisible(true);
    this.setPreferredSize(size);
    this.setMaximumSize(size);
    this.setLayout(gridBagLayout3);
    Table1.setBackground(Color.white);
    Table1.setEnabled(false);
    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = 1;
    c.ipady = 10;
    c.gridwidth = 100;
    c.anchor = GridBagConstraints.NORTHWEST;
    gridBagLayout3.setConstraints(hel,c);
    this.add(hel);
    this.add(Table1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
    ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 74, 500));
    class Table1Model extends AbstractTableModel
    Object[][] Table1Data =
    {"Address",new String()},
    {"Serial #" ,new String()},
    {"SW Revision" ,new String()},
    {"ETM" ,new String()},
    {"T1",new String()},
    {"T2" ,new String()},
    {"TC/Vac Gauge" ,new String()},
    {"Aux TC" ,new String()},
    {"Motor Speed",new String()},
    {"Set Values" ,new String()},
    {"Heater Pwr T1" ,new String()},
    {"Heater Pwr T2" ,new String()},
    public void setValueAt (Object value, int row, int col)
         Table1Data[row][col] = value;
         public int getColumnCount()
    return Table1Data[0].length;
    public int getRowCount()
    return Table1Data.length;
    /* public String getColumnName(int col)
    return (String)headers[col];
    public Object getValueAt(int row,int col)
    return Table1Data[row][col];
    };

    Thanks Denis.
    I did this:
    JScrollPane scroll = new JScrollPane(Table1);
    this.add(scroll, new GridBagConstraints(0, 0, 1, 3, 1.0, 1.0
    ,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 74, 500));
    That works but I want to see the whole table at once. Is there something I can do to do that?

  • Problems with basic Java JPanel animation using paintcomponent

    okay so I am trying to animate a sprite moving across a background using a for loop within the paintComponent method of a JPanel extension
    public void paintComponent(Graphics g){
    Image simpleBG = new ImageIcon("Images/Backgrounds/Simple path.jpg").getImage();
    Image mMan = new ImageIcon("Images/Sprites/hMan.gif").getImage();
    if (!backgroundIsDrawn){
    g.drawImage(simpleBG, 0, 0, this);
    g.drawImage(mMan, xi, y, this);
    backgroundIsDrawn=true;
    else
    for (int i=xi; i<500; i++){
    g.drawImage(simpleBG, 0, 0, this);
    g.drawImage(mMan, i, y, this);
    try{
    Thread.sleep(10);
    } catch(Exception ex){System.out.println("damn");}
    The problem is that no matter what I set my thread to, it will not show the animation, it will just jump to the last location, even if the thread sleep is set high enough that it takes several minutes to calculate,, it still does not paint the intemediary steps.
    any solution, including using a different method of animation all together would be greatly appreciated. I am learning java on my own so i need all the help I can get.

    fysicsandpholds1014 wrote:
    even when I placed the thread sleep outside of the actual paintComponent in a for loop that called repaint(), it still did not work? Nope. Doing this will likely put the Event Dispatch Thread or EDT to sleep. Since this is the main thread that is responsible for Swing's painting and user interaction, you'll put your app to sleep with this. Again, use a Swing Timer
    and is there any easy animation method that doesnt require painting and repainting every time becasue it is very hard to change what I want to animate with a single paintComponent method? I don't get this.
    I find the internet tutorials either way too complicated or not nearly in depth enough. Maybe its just that I am new to programming but there doesn't seem to be a happy medium between dumbed down Swing tutorials and very complicated and sophisticated animation algorithmns.I can only advise that you practice, practice, practice. The more you use the tutorials, the easier they'll be to use.
    Here's another small demo or animation. It is not optimized (repaint is called on the whole JPanel), but demonstrates some points:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    @SuppressWarnings("serial")
    public class AnimationDemo2 extends JPanel {
      // use a publicly available sprite for this example
      private static final String SPRITE_PATH = "http://upload.wikimedia.org/" +
                "wikipedia/commons/2/2e/FreeCol_flyingDutchman.png";
      private static final int SIDE = 600;
      private static final Dimension APP_SIZE = new Dimension(SIDE, SIDE);
      // timer delay: equivalent to the Thread.sleep time
      private static final int TIMER_DELAY = 20;
      // how far to move in x dimension with each loop of timer
      public static final int DELTA_X = 1;
      // holds our sprite image
      private BufferedImage img = null;
      // the images x & y locations
      private int imageX = 0;
      private int imageY = SIDE/2;
      public AnimationDemo2() {
        setPreferredSize(APP_SIZE);
        try {
          // first get our image
          URL url = new URL(SPRITE_PATH);
          img = ImageIO.read(url);
          imageY -= 3*img.getHeight()/4;
        } catch (Exception e) { // shame on me for combining exceptions :(
          e.printStackTrace();
          System.exit(1); // exit if fails
        // create and start the Swing Timer
        new Timer(TIMER_DELAY, new TimerListener()).start();
      // all paintComponent does is paint -- nothing else
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.blue);
        int w = getWidth();
        int h = getHeight();
        g.fillRect(0, h/2, w, h);
        if (img != null) {
          g.drawImage(img, imageX, imageY, this);
      private class TimerListener implements ActionListener {
        // is called every TIMER_DELAY ms
        public void actionPerformed(ActionEvent e) {
          imageX += DELTA_X;
          if (imageX > getWidth()) {
            imageX = 0;
          // ask JVM to paint this JPanel
          AnimationDemo2.this.repaint();
      // code to place our JPanel into a JFrame and show it
      private static void createAndShowUI() {
        JFrame frame = new JFrame("Animation Demo");
        frame.getContentPane().add(new AnimationDemo2());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      // call Swing code in a thread-safe manner
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
    }

  • Transition [cant remove old JPanel]

    Hello!
    I want to make transition between two JPanels(actually objects based ont them..)
    I can hide splashpanel from Frame.java, but cant from SplashPanel.java
    I know i am doing somethin really wrong, but dont know what.
    So here is the code.
    Frame.java
    package ui;
    import javax.swing.*;
    import net.miginfocom.swing.MigLayout;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.Deque;
    import java.util.Stack;
    @SuppressWarnings("serial")
    public class Frame extends JFrame {
         public Frame() {
              // Set default size and position of screen
              Toolkit toolkit = Toolkit.getDefaultToolkit();
              Dimension scrSize = toolkit.getScreenSize();
              int scrX = scrSize.width;
              int scrY = scrSize.height;
              int X = (scrX - 750) / 2;
              int Y = (scrY - 550) / 2;
              setSize(750, 550);
              setLocation(X, Y);
              setTitle("Blood of a shadow");
              Image bloodlogo = toolkit
                        .getImage("E:\\Java\\Blood of a Shadow\\src\\ui\\bloodlogo.gif");
              setIconImage(bloodlogo);
              showsplashpanel();
              //clearAll();
         public void showsplashpanel() {
              SplashPanel splashpanel = new SplashPanel();
              add(splashpanel);
         public void clearAll() {
              System.out.println("It came to clearAll method of Frame class");
              removeAll();
              validate();
              repaint();
              System.out.println("an to the end...  damn");
    }SplashPanel.java
    package ui;
    import java.awt.Color;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JPanel;
    import net.miginfocom.swing.MigLayout;
    @SuppressWarnings("serial")
    public class SplashPanel extends JPanel{
         public SplashPanel() {
              setFocusable(true);
              KeyListener keylistener = new KeyListener() {
                   public void keyPressed(KeyEvent e) {
                        char key=e.getKeyChar();
                        int keycode=e.getKeyCode();
                        if(keycode==65) {
                             new Frame().clearAll();
                        System.out.println(key+" | code: "+keycode);
                    public void keyReleased(KeyEvent e) {
                    public void keyTyped(KeyEvent e) {
              addKeyListener(keylistener);
              MigLayout layout = new MigLayout("gap 20px 15px");
              setLayout(layout);
              setBackground(Color.BLACK);
              ShadowLabel newgame = new ShadowLabel("New Game");
              ShadowLabel loadgame = new ShadowLabel("Load Game");
              ShadowLabel help = new ShadowLabel("Help");
              ShadowLabel author = new ShadowLabel("About author");
              add(newgame, "wrap");
              add(loadgame,"wrap");
              add(help,"wrap");
              add(author,"wrap");
    }keycode 65 = a or A
    Thanks in advance!
    GrizzLy

    Nevermind, i solved it!

  • Serializing Vectors that are in other classes

    If I have...
    public MyPanel extends Jpanel implements serializable
    private vector d;
    public MyPanel()
    d=new Vector();
    public void paint comp(gra g)//etc
    Part f=(part)d.get(i);//etc
    d.draw(g)
    and i OutputStream.write(MyPanel); and InputStream.read(MYpanel) is the vector serialized as well?(Yes the objects "(Part)"within the vector are/is serializable) because when i do:
    MyPanel g=(MyPanel)in.readObject();
    and then MyFrame.setMyPanel(g);
    the vector becomes empty!! and the parts in the vector can no longer be drawn;
    help?
    dev

    I am not sure what the problem is, but,
    - The vector class is Serializable (it isn't the spelling (capital 's') is it??).
    OR
    - Should it be JPanel g=(MyPanel)in.readObject();
    OR
    - How do you actually get the vector as there is no accessor method and the vector is private? Could it be you are just not getting the vector because of this.
    Please ignore this if I am talking rubbish (it is late).

  • How to detect serial port

    CommPortIdentifier portId;
              Enumeration en = CommPortIdentifier.getPortIdentifiers();
              Vector v=new Vector();
              while (en.hasMoreElements())
                   portId = (CommPortIdentifier) en.nextElement();
                   if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
                             v.addElement(portId.getName());
              }

    refer this URL
    http://www.java2s.com/Code/Java/Development-Class/ReadfromaSerialportnotifyingwhendataarrives.htm
         * Project                     :
         * Class                     : GUIFrame.java
         * Purpose                    :
         * Date_Created               :
         * @ Version 1.0
    import javax.swing.JFrame;
    // import javax.swing.JPanel;
    import javax.swing.JMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import java.awt.event.*;
    import javax.comm.*;
    import java.awt.*;
    import javax.swing.*;
    // import javax.swing.border.TitledBorder;     
    public class GUIFrame extends JFrame implements ActionListener
         JButton connectPort;
         JComboBox combo;     
         //JButton baudRate;
         //JComboBox baudRateCombo;     
         public JTextArea textArea;     
         JButton sendData;
         public SerialConnection serialConnection;
         public GUIFrame()
              setLayout(null);
              setTitle("First Frame");
              serialConnection = new SerialConnection();                    
              setJMenuBar(createMenuBar());
              combo = new JComboBox();
              combo.setBounds(50, 50, 80, 25);
              listPort();
              combo.addActionListener(this);
              connectPort = new JButton("Connect");
              connectPort.setBounds(150, 50, 100, 25);
              connectPort.addActionListener(this);
              sendData = new JButton("Send Data");
              sendData.setBounds(150, 150, 100, 25);
              sendData.addActionListener(this);
              textArea = new JTextArea();
              textArea.setBounds(300, 300, 400, 300);
              textArea.setFont(new Font("sansserif",0,18));
              add(connectPort);
              add(combo);
              add(sendData);
              add(textArea);;
              setSize(400, 300);
              setVisible(true);
              addWindowListener(new MainWindowAdapter());
         public static void main(String arg[])
              System.out.println("Hi");
              new GUIFrame();
         public JMenuBar createMenuBar()
              JMenuBar menuBar = new JMenuBar();
              JMenu fileMenu = new JMenu("File");
              JMenuItem connectMenuItem = new JMenuItem("Connect");
              connectMenuItem.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae){
                        try{
                             if(serialConnection.portName == null){
                                  serialConnection.portName = combo.getSelectedItem().toString();
                             serialConnection.openConnection();
                        catch(Exception ex)
              JMenuItem disconnectMenuItem = new JMenuItem("Disconnect");
              disconnectMenuItem.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae){
                        try{
                             serialConnection.closeConnection();
                        catch(Exception ex)
              fileMenu.add(connectMenuItem);
              fileMenu.add(disconnectMenuItem);
              menuBar.add(fileMenu);
              return menuBar;
         public void listPort()
              CommPortIdentifier portId;          
              java.util.Enumeration enumeration = CommPortIdentifier.getPortIdentifiers();
              while(enumeration.hasMoreElements())
                   portId = (CommPortIdentifier)enumeration.nextElement();
                   if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
                        if(!portId.isCurrentlyOwned())
                             combo.addItem(portId.getName());
         public void actionPerformed(ActionEvent ae)
              if(ae.getSource() == connectPort)
                   System.out.println("Connect is clicked");     
                   try
                        if(serialConnection.portName == null)
                             serialConnection.portName = combo.getSelectedItem().toString();
                        serialConnection.openConnection();
                   catch(Exception ex)
              if(ae.getSource() == combo)
                   System.out.print("Port Name = " + combo.getSelectedItem().toString());
                   serialConnection.portName = combo.getSelectedItem().toString();
              if(ae.getSource() == sendData)
                   byte b[] = new byte[5];
                   b[0] = (byte)0xaa;
                   b[1] = (byte)0xbb;
                   b[2] = (byte)0xcc;
                   b[3] = (byte)0xdd;
                   b[4] = (byte)0xee;     
                   try
                        serialConnection.getOutputStream().write(b);
                        display(b);
                   catch(Exception ex)
         public class MainWindowAdapter extends WindowAdapter
              public void windowClosing(WindowEvent win)
                   dispose();
                   System.exit(0);
         public void display(byte[] b)
              for(int i=0; i< b.length; i++)
                   textArea.append(Integer.toHexString (b[i] & 0xff) + " ");
              textArea.append("\n");
         * Project                     :
         * Class                     : SerialConnection.java
         * Purpose                    :
         * Date_Created               :
         * @ Version 1.0
    import javax.comm.*;
    import java.io.*;
    public class SerialConnection
         private OutputStream os;
         private InputStream is;
         private CommPortIdentifier portId;
         public SerialPort sPort;
         private boolean open;
         public String portName;
         SerialConnection serialConnection;
         public SerialConnection()
              serialConnection=this;
              PortHandler portHandler = new PortHandler(serialConnection);
              portHandler.init(serialConnection);
         public void setOutputStream(OutputStream os)
              this.os=os;
         public OutputStream getOutputStream()
              return os;
         public void setInputStream(InputStream is)
              this.is=is;
         public InputStream getInputStream()
              return is;
         * A Method to open the SerialConnection
    public void openConnection() throws Exception
              try
                   portId = CommPortIdentifier.getPortIdentifier(portName);
              catch (javax.comm.NoSuchPortException e)
                   System.out.println("noPort : "+e);
              try
                   sPort = (SerialPort)portId.open("port", 3000);               
                   open = true;
              catch (javax.comm.PortInUseException e)
                   throw new Exception();
              try
                   setOutputStream(sPort.getOutputStream());
                   setInputStream(sPort.getInputStream());               
                   System.out.println("IO stream is opened");
              catch (java.io.IOException e)
                   sPort.close();                    
         *A Method to Close the port and clean up associated elements.
         public void closeConnection()
              // If port is already closed just return.
              if (!open)
                   return;
              if (sPort != null)
                   try
                        this.os.close();
                        this.is.close();
                        System.out.println("IO stream is opened - CloseConnection");
                   catch (java.io.IOException e)
                        System.err.println(e);
                   sPort.close();
                   System.out.println("Port is closed");
              System.out.println("Flag Open - 1 : " + open );
              open = false;
              System.out.println("Flag Open - 2 : " + open);
         * Send a one second break signal.
         public void sendBreak()
              sPort.sendBreak(1000);
         * Reports the open status of the port.
         * @return true if port is open, false if port is closed.
         public boolean isOpen()
              return open;
         * A Method to add the event listener to the SerialPort
         public void addEventListener(java.util.EventListener listener)throws Exception
              System.out.println("Is not in opened state");
              if(isOpen())
                   System.out.println("Is in opened state");
                   try
                        sPort.addEventListener((javax.comm.SerialPortEventListener)listener);
                   catch (java.util.TooManyListenersException e)
                        sPort.close();               
                   // Set notifyOnDataAvailable to true to allow event driven input.
                   sPort.notifyOnDataAvailable(true);
                   // Set notifyOnBreakInterrup to allow event driven break handling.
                   sPort.notifyOnBreakInterrupt(true);
                   // Set receive timeout to allow breaking out of polling loop during
                   // input handling.
                   try
                   sPort.enableReceiveTimeout(50);
                   //sPort.enableReceiveTimeout(-1);
                   catch (javax.comm.UnsupportedCommOperationException e)
                        e.printStackTrace();
                   // Add ownership listener to allow ownership event handling.
                   portId.addPortOwnershipListener((javax.comm.CommPortOwnershipListener)listener);
         import javax.comm.*;
         public class PortHandler implements SerialPortEventListener,CommPortOwnershipListener{
              public SerialConnection serialConnection;
              public PortHandler(SerialConnection serialConnection)
                   this.serialConnection=serialConnection;
                   try{
                        serialConnection.addEventListener((SerialPortEventListener)this);
                        System.out.println("New Port Handler is called");
                   catch(Exception e)
                        System.out.println("Exception PortHandler(); " +e);
                        e.printStackTrace();
                   // Add this object as an event listener for the serial port.
                   System.out.println("PortHandler is initialised...");
              public SerialConnection getConnection(){
                   return serialConnection;
              public void setSerialConnection(SerialConnection serialConnection){
                   this.serialConnection = serialConnection;
              public void init(SerialConnection serialConnection){
                   setSerialConnection(serialConnection);
              public void serialEvent(SerialPortEvent e){
                   System.out.println("Event Initialised");
                   //Determine type of event.
                   switch (e.getEventType())
                        case SerialPortEvent.DATA_AVAILABLE:
                             try{
                                  readData();                              
                             catch(java.io.IOException e1)
                                  System.out.println("IO Excep "+e1.getMessage());
                                  e1.printStackTrace();
                             catch(Exception e1)
                                  System.out.println("Exception from Serial Event "+e1.getMessage());
                                  e1.printStackTrace();
                        break;
                        case SerialPortEvent.BI:
                        break;
              public void readData() throws java.io.IOException
                   byte b[]=new byte[8500];
                   int i=0,selectOption=0;
                   int newData=0;
                   int doubleLength=0;
                   int length=0;
                   // String mid="",strLen="";
                   while (newData != -1)
                        try     
                             System.out.println("getInputStream().available() : " + serialConnection.getInputStream().available());
                             newData = serialConnection.getInputStream().read();
                             System.out.println("newData\t"+newData);
                             if (newData == -1)
                                  System.out.println("\n End of the File\n");
                                  break;
                             if(i==0){
                                  b=(byte)newData;
                                  System.out.print("\n MSg ID \t= " + Integer.toString(newData&0xff,16)+"\n----------------------------");
                                  if(b[0] == (byte)0x00)
                                       i=-1;
                                       i++;
                                       continue;
                                  i++;
                                  //System.out.println("Method is called - selectOption : " + selectOption);
                                  continue;
                             if(i==1)
                                  b[i]=(byte)newData;
                                  System.out.print("\n Length =\t"+Integer.toString(newData&0xff,16)+"\n----------------------------");
                                  length=newData;
                                  if(length == 0)
                                       i=0;
                                       continue;
                                  i++;
                                  continue;
                             b[i]=(byte)newData;
                             if((b[0] == (byte)0x07) && (i == 2) || (b[0] == (byte)0xaf) && (i == 2) || (b[0] == (byte)0xec) && (i == 2)
                                  || (b[0] == (byte)0x5c) && (i == 2) || (b[0] == (byte)0xbe) && (i == 2) )
                                  String string = String.valueOf((byte)b[0]);
                                  String strLen = Integer.toString(b[2]&0xff,16) + Integer.toString(b[1]&0xff,16);
                                  System.out.println("\n\nLength String = " + strLen + "\n\n");
                                  java.math.BigInteger bi=new java.math.BigInteger(strLen,16);
                                  strLen = bi.toString();
                                  doubleLength = Integer.parseInt(strLen);
                                  System.out.println("\nLength int = " + doubleLength + "\n");
                                  //System.out.println("Method is called");
                             i++;
                             // Added by Siva on Jan 06
                             switch(selectOption)
                                  case 0:
                                       if(i>length+1)
                                            try
                                                 b[i]=(byte)newData;     
                                                 System.out.print("\nThe Last Byte =\t"+Integer.toString(newData&0xff,16)+"\n----------------------------");
                                                 System.out.print("\n"+i+" i Value =\t"+Integer.toString(newData&0xff,16));
                                                 System.out.println("\n----------------------- FINISHED------------------------------");
                                                 // service(b);     
                                                 System.out.println("\n----------------------- After Service------------------------------");
                                                 i=-1;
                                                 i++;               
                                                 continue;
                                            }catch (Exception e)
                                                 System.out.println("Exception in calling service 0:"+e.getMessage());
                                                 e.printStackTrace();
                                                 b[i]=(byte)newData;
                                       System.out.print("\nMSg ID \t= "+Integer.toString(newData&0xff,16)+"\n----------------------------");
                                       break;
                   }catch (java.io.IOException ex)     {
                        System.err.println("Abstarct Port handler Exception\t"+ex);
                   catch(Exception e1)
                        System.out.println("Exception from Read Data "+e1.getMessage());
                        e1.printStackTrace();
                   System.out.println("-----------------------------");
              public void ownershipChange(int type){
                   if (type == CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED){
              public void destroy()     
                   try{
                        serialConnection.closeConnection();     
                   }catch(Exception e){
                        System.out.println("Exception 2:"+e);     
                        e.printStackTrace();
              public void finalize(){
                   destroy();

  • Saving a custom JPanel

    i have a custom jpanel that stores works similary to a drawing tool all classes used inside it are serializable as a result does that mena to save it i can simple serialize the class then when come to load just deserialize is and it should work?

    As JavaDoc says:
    * Portable and version resilient
    * Structurally compact
    * Fault tolerant
    And it's the recomeded way of serailization for **swing**.
    In other words, a xml serialization is "compatible" (to a certain extent) beetween versions of the classes, is more compact because if the property don't change from the original (from a instance without modifications of the bean) it's not serialized. Try to serialize with XMLEncoder and open the document generated. The way the component's graph is reconstructed is very interesting and you can understand why xml serialization is best.
    A personal serialization is needed when the objects you need are too complex

  • Serializing a Panel...

    Hi there
    I want to save the content of the programmatically buttons in the Panel. However, sometimes I got the following exception and I really can't work out why. Please help I really can't work it out.
    java.io.NotSerializableException: javax.swing.DefaultPopupFactory      at java.io.ObjectOutputStream.outputObject(ObjectOutputStream.java:1148)      at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:366)      at java.io.ObjectOutputStream.outputClassFields(ObjectOutputStream.java:1827)      at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:480)      at java.io.ObjectOutputStream.outputObject(ObjectOutputStream.java:1214)      at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:366)      at java.awt.Window.writeObject(Window.java:1048)      at java.lang.reflect.Method.invoke(Native Method)      at java.io.ObjectOutputStream.invokeObjectWriter(ObjectOutputStream.java:1864)      at java.io.ObjectOutputStream.outputObject(ObjectOutputStream.java:1210)      at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:366)      at java.io.ObjectOutputStream.outputClassFields(ObjectOutputStream.java:1827)      at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:480)      at java.io.ObjectOutputStream.outputObject(ObjectOutputStream.java:1214)      at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:366)      at Assignment1$5.actionPerformed(Assignment1.java:142)      at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1450)      at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1504)      at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:378)      at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:250)      at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:216)      at java.awt.Component.processMouseEvent(Component.java:3715)      at java.awt.Component.processEvent(Component.java:3544)      at java.awt.Container.processEvent(Container.java:1164)      at java.awt.Component.dispatchEventImpl(Component.java:2593)      at java.awt.Container.dispatchEventImpl(Container.java:1213)      at java.awt.Component.dispatchEvent(Component.java:2497)      at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:2451)      at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2216)      at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2125)      at java.awt.Container.dispatchEventImpl(Container.java:1200)      at java.awt.Window.dispatchEventImpl(Window.java:926)      at java.awt.Component.dispatchEvent(Component.java:2497)      at java.awt.EventQueue.dispatchEvent(EventQueue.java:339)      at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)      at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
    My source code.
    import java.awt.*;
    import javax.swing.*;
    import java.io.Serializable;
    public interface AbstractPanel extends Serializable{
         public void addButton(String s);
         public void updateButton(String s);
         public void deleteButton();
         public void setPanel(Container content, JPanel panel3);
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import java.util.*;
    public class BorderLayoutPanel extends JPanel implements AbstractPanel {
         private Assignment1 parent;
         protected JComboBox comboBox = new JComboBox();
         private Vector buttons = new Vector();
         public BorderLayoutPanel(Assignment1 pt) {
              super();
              parent = pt;          
              setLayout(new BorderLayout());
              TitledBorder title1 = BorderFactory.createTitledBorder("Subject JPanel");
              setBorder(title1);                    
              comboBox.addItem(BorderLayout.NORTH);
              comboBox.addItem(BorderLayout.SOUTH);
              comboBox.addItem(BorderLayout.WEST);
              comboBox.addItem(BorderLayout.EAST);
              comboBox.addItem(BorderLayout.CENTER);          
         public void addButton(String s) {
              JButton newb = new JButton(s);
              buttons.add(newb);
              newb.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ev) {
                        parent.clicked = (JButton) ev.getSource();
                        parent.text.setText(parent.clicked.getText());
                        parent.update.setEnabled(true);
                        parent.delete.setEnabled(true);
              add(newb, ((String) comboBox.getSelectedItem()) );
              validate();
              repaint();
         public void updateButton(String s) {
              remove(parent.clicked);
              parent.clicked.setText(s);
              add(parent.clicked, ((String) parent.comboBox.getSelectedItem()) );
              parent.update.setEnabled(false);
              parent.delete.setEnabled(false);
              validate();
              repaint();
         public void deleteButton() {
              remove(parent.clicked);
              parent.update.setEnabled(false);
              parent.delete.setEnabled(false);
              validate();
              repaint();
         public void setPanel(Container content, JPanel panel3) {
              panel3.setLayout(new BorderLayout());
              panel3.add(comboBox, BorderLayout.WEST);
              content.validate();
              content.repaint();     
    Thank you for any suggest and advice!
    Edmond

    Hi there,
    I have found that after I click on the JComboBox, I will get the exception. Does anyone know if there is any special about serializing the JComboBox? Or, is there a bug in it?
    Thank you!

Maybe you are looking for

  • Creating a Custom SAPscript Editor

    I am trying to create a custom SAPscript editor and I'm having problems. We are on SAP 640. We use texts to store notes against invoices recording details of the dunning process. Our users have ask if we can tailor the notes so that users can insert

  • Open detail report in same window(same frame) in BI Publisher11.1.6.0

    Hi I have created 2 reports Master Report - Interactive view template Detail Report - Interactive view template I have given detail report hyperlink in Master report. when i click on the link, it opens in new tab or window instead of opening in same

  • Issue while posting through MIRO

    Hi, I am posting through MIRO. I am using two POs in MIRO from different contracts. When I add them for one PO amount and QTY feild is filled up properly, but for other the value of QYT is filled into amount and qty field. Could any one help in solvi

  • Frm-40375 and ora-306500 with ODBC connection

    Hi experts, I am getting frm-40375 , ora-306500 when clicking a button on form , the code behind the button is actually connecting to a database other than oracle using the ODBC connection and importing data in variables and than inserting in an orac

  • Setting up a Role to Restrict SQVI by user (on field BUKRS table KNC3)

    Hi Everyone! I am trying to get my basis team to give me access to SQVI - but they want to restrict the financial data I have access to by company code (9000 in our company). The authorisation checking for SQVI is not straightforward apparently. It d