Problem with setVisible

Hi
I made a class like this.
class MonthComboBox extends JComboBox
public MonthComboBox()
addItem(" ");
addItem("Jan");
addItem("Feb");
addItem("Mar");
addItem("Apr");
addItem("May");
addItem("Jun");
addItem("Jul");
addItem("Aug");
addItem("Sep");
addItem("Oct");
addItem("Nov");
addItem("Dec");
Now when I tried to do <object>.setVisible(false) in an event handler
the runtime environment started giving lots of exceptions. Can somebody tell me whats wrong and how to correct this?

Here is a simple program to hide the combobox, hope it helps.
If this does not help, then -as already suggested- you have to provide us a little bit more information about your code and exceptions. =)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MonthComboBox extends JComboBox implements ActionListener
     public MonthComboBox()
          addItem(" ");
          addItem("Jan");
          addItem("Feb");
          addItem("Mar");
          addItem("Apr");
          addItem("May");
          addItem("Jun");
          addItem("Jul");
          addItem("Aug");
          addItem("Sep");
          addItem("Oct");
          addItem("Nov");
          addItem("Dec");
     public void actionPerformed(ActionEvent e)
     if(isVisible())
     setVisible(false);
else
     setVisible(true);
     public static void main(String [] args)
          //Make JPanel for the combobox
          JPanel mainPanel = new JPanel();
          mainPanel.setLayout(new BorderLayout());
          final MonthComboBox combo = new MonthComboBox();
          mainPanel.add(combo,BorderLayout.WEST);
          //Button that hides the combobox
          JButton button = new JButton("Toggle ComboBox Visibility");
          //Add an actionlistener for the button
          //in this case the combobox itself listens to it's own actions
          button.addActionListener(combo);
     mainPanel.add(button,BorderLayout.EAST);
          //Create a frame to test the code
          JFrame frame = new JFrame("Testing");
          frame.getContentPane().add(mainPanel);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setSize(300,70);
          frame.setVisible(true);
Br,
J

Similar Messages

  • Problem with setVisible(true) ??

    Hi All;
    In my application, I am using JFrame and added some component. At last I called setVisible(true); method. But it cann't works.
    Then I tried with show() method. but the result is same.
    Then I tried with isDisplayable() method, but strange ,it is returning false.
    Now my problem is why it is hanging on calling the setVisible() method. or why it is returning false for isDisplayable().
    Can anybody guide me to solve the problem.
    Thanks in advance.
    -Sumeet G

    You should pack() or validate() the frame before
    calling setVisible(). Do pack if you use layout
    managers, validate if you set components size
    manually.

  • I have a problem with setVisible(true) !!!!!!

    Hi!
    Could you tell me please, how can I use the method
    getSize() before call the method setVisible(true)??
    If I call the method getSize() before setVisible(true)
    then return getSize() only 0 !!!!!
    I must call getSize() before setVisible(true).
    Thank you for your help ;-))
    Code:
    import java.awt.*;
    class Test extends Frame
    Test()
    t.setSize(200, 100);
    Button b=new Button("test");
    t.add(b);
    System.out.println("Size: "+ b.getSize()); //It doesn't work!!!!
    t.setVisible(true); // ohne das haut's ihn raus !
    public static void main(String args[])
    (new Test());
    }

    If you want to get the Button size, then you should set the button size before you called getSize(), otherwise you will get the value of zero just like yours.
    Try the following code.
    import java.awt.*;
    class Test extends Frame
    Test()
    setSize(200, 100);
    Button b=new Button("test");
    b.setSize(70,25);
    add(b);
    System.out.println("Size: "+ b.getSize()); //It doesn't work!!!!
    setVisible(true); // ohne das haut's ihn raus !
    public static void main(String args[])
    new Test();
    In this way, you will get the button size!

  • Problem with setVisible(false)

    I everybody!!
    I have a some panels in a JFrame, disposed ones underneath the others. But when I make one of the bottom invisble doing:
    jPanel.setVisible(false);
    the ones in the top becomes down!!
    Is there any way to avoid this?
    Thanks in advance

    If you have multiple panels sharing the same area in a JFrame then you should be using a [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]Card Layout.
    Or you need to remove the old panel before adding the new panel.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.

  • Problem with jDialog in a JFrame

    Hello to everyone...i'm newby java GUI developer, and i've got a problem with a JDialog within a JFrame...
    I made a JFrame which creates a new customized JDialog in his contructor, like this:
    MioJdialog dlg = new MioJdialog(this, true);
    dlg.setVisible(true);
    ...The "MioJdialog" class store his JFrame parent under a private attribute, in this way:
    class MioJdialog {...
    private Frame parent;
    public MioJdialog (Frame parent, boolean modal){
        this.parent=parent;
    ....}and here's the problem: when i try to close the parent JFrame with a command like this:
    parent.dispose();
    ( in order to close the whole window), sometimes happens that the JFrame is still visible on the screen...and i don't know why...
    got some hints?
    thanks to everyone!
    Edited by: akyra on Jan 14, 2008 4:36 AM
    Edited by: akyra on Jan 14, 2008 4:37 AM
    Edited by: akyra on Jan 14, 2008 4:37 AM

    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html
    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting

  • Problem with JFrame and busy/wait Cursor

    Hi -- I'm trying to set a JFrame's cursor to be the busy cursor,
    for the duration of some operation (usually just a few seconds).
    I can get it to work in some situations, but not others.
    Timing does seem to be an issue.
    There are thousands of posts on the BugParade, but
    in general Sun indicates this is not a bug. I just need
    a work-around.
    I've written a test program below to demonstrate the problem.
    I have the problem on Solaris, running with both J2SE 1.3 and 1.4.
    I have not tested on Windows yet.
    When you run the following code, three JFrames will be opened,
    each with the same 5 buttons. The first "F1" listens to its own
    buttons, and works fine. The other two (F2 and F3) listen
    to each other's buttons.
    The "BUSY" button simply sets the cursor on its listener
    to the busy cursor. The "DONE" button sets it to the
    default cursor. These work fine.
    The "SLEEP" button sets the cursor, sleeps for 3 seconds,
    and sets it back. This does not work.
    The "INVOKE LATER" button does the same thing,
    except is uses invokeLater to sleep and set the
    cursor back. This also does not work.
    The "DELAY" button sleeps for 3 seconds (giving you
    time to move the mouse into the other (listerner's)
    window, and then it behaves just like the "SLEEP"
    button. This works.
    Any ideas would be appreciated, thanks.
    -J
    import java.awt.BorderLayout;
    import java.awt.Cursor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class BusyFrameTest implements ActionListener
    private static Cursor busy = Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR);
    private static Cursor done = Cursor.getDefaultCursor();
    JFrame frame;
    JButton[] buttons;
    public BusyFrameTest (String title)
    frame = new JFrame (title);
    buttons = new JButton[5];
    buttons[0] = new JButton ("BUSY");
    buttons[1] = new JButton ("DONE");
    buttons[2] = new JButton ("SLEEP");
    buttons[3] = new JButton ("INVOKE LATER");
    buttons[4] = new JButton ("DELAY");
    JPanel buttonPanel = new JPanel();
    for (int i = 0; i < buttons.length; i++)
    buttonPanel.add (buttons);
    frame.getContentPane().add (buttonPanel);
    frame.pack();
    frame.setVisible (true);
    public void addListeners (ActionListener listener)
    for (int i = 0; i < buttons.length; i++)
    buttons[i].addActionListener (listener);
    public void actionPerformed (ActionEvent e)
    System.out.print (frame.getTitle() + ": " + e.getActionCommand());
    if (e.getActionCommand().equals ("BUSY"))
    frame.setCursor (busy);
    else if (e.getActionCommand().equals ("DONE"))
    frame.setCursor (done);
    else if (e.getActionCommand().equals ("SLEEP"))
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    else if (e.getActionCommand().equals ("INVOKE LATER"))
    frame.setCursor (busy);
    SwingUtilities.invokeLater (thread);
    else if (e.getActionCommand().equals ("DELAY"))
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    System.out.println();
    Runnable thread = new Runnable()
    public void run()
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.println (" finished");
    public static void main (String[] args)
    BusyFrameTest f1 = new BusyFrameTest ("F1");
    f1.addListeners (f1);
    BusyFrameTest f2 = new BusyFrameTest ("F2");
    BusyFrameTest f3 = new BusyFrameTest ("F3");
    f2.addListeners (f3); // 2 listens to 3
    f3.addListeners (f2); // 3 listens to 2

    I've had the same problems with cursors and repaints in a swing application, and I was thinking of if I could use invokeLater, but I never got that far with it.
    I still believe you would need a thread for the time consuming task, and that invokeLater is something you only need to use in a thread different from the event thread.

  • Can some one help me with this problem with my frame???

    i have gt a veri strange problem with my program,that is teh graphic changes only when i resize the the frame,if i dun resize,it will remain the same.However what i intended is that when i click on the radio button,it will change immediately to the respective pages.A simple version of my code is below,can someone helpl me solve it??(there is 3 different class)
    import java.awt.event.*;
    import javax.swing.*;
    public class MainPg extends JFrame implements ActionListener{
         private javax.swing.JPanel jContentPane = null;
         private javax.swing.JPanel buttons = null;
         private javax.swing.JRadioButton one = null;
         private javax.swing.JRadioButton two = null;
         private javax.swing.JPanel change = null;
         public MainPg() {
              super();
              initialize();
         private void initialize() {
              this.setSize(300, 200);
              this.setContentPane(getJContentPane());
              this.setName("mainClass");
              this.setVisible(true);
         private javax.swing.JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(new java.awt.BorderLayout());
                   jContentPane.add(getButtons(), java.awt.BorderLayout.WEST);
                   jContentPane.add(getChange(), java.awt.BorderLayout.CENTER);
              return jContentPane;
         private javax.swing.JPanel getButtons() {
              if(buttons == null) {
                   buttons = new javax.swing.JPanel();
                   java.awt.GridLayout layGridLayout1 = new java.awt.GridLayout();
                   layGridLayout1.setRows(2);
                   layGridLayout1.setColumns(1);
                   ButtonGroup group=new ButtonGroup();
                   group.add(getOne());
                   group.add(getTwo());
                   buttons.setLayout(layGridLayout1);
                   buttons.add(getOne(), null);
                   buttons.add(getTwo(), null);
              return buttons;
         private javax.swing.JRadioButton getOne() {
              if(one == null) {
                   one = new javax.swing.JRadioButton();
                   one.setText("One");
                   one.setSelected(true);
                   one.addActionListener(this);
                   one.setActionCommand("one");
              return one;
         private javax.swing.JRadioButton getTwo() {
              if(two == null) {
                   two = new javax.swing.JRadioButton();
                   two.setText("Two");
                   two.addActionListener(this);
                   two.setActionCommand("two");
              return two;
         private javax.swing.JPanel getChange() {
              if(change == null) {
                   change = new javax.swing.JPanel();
              change.add(new One());
              return change;
         public static void main(String[] args){
              new MainPg();
         public void actionPerformed(ActionEvent e) {
              change.removeAll();
              if("one".equals(e.getActionCommand())){
                   change.add(new One());
              else{
                   change.add(new Two());
              change.repaint();
    import javax.swing.*;
    public class One extends JPanel {
         private javax.swing.JPanel jPanel = null;
         private javax.swing.JLabel jLabel = null;
         private javax.swing.JPanel jPanel1 = null;
         private javax.swing.JLabel jLabel1 = null;
         private javax.swing.JLabel jLabel2 = null;
         public One() {
              super();
              initialize();
         * This method initializes this
         * @return void
         private void initialize() {
              this.setLayout(new java.awt.BorderLayout());
              this.add(getJPanel(), java.awt.BorderLayout.NORTH);
              this.add(getJPanel1(), java.awt.BorderLayout.WEST);
              this.setSize(300, 200);
         * This method initializes jPanel
         * @return javax.swing.JPanel
         private javax.swing.JPanel getJPanel() {
              if(jPanel == null) {
                   jPanel = new javax.swing.JPanel();
                   jPanel.add(getJLabel(), null);
              return jPanel;
         * This method initializes jLabel
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel() {
              if(jLabel == null) {
                   jLabel = new javax.swing.JLabel();
                   jLabel.setText("one");
              return jLabel;
         * This method initializes jPanel1
         * @return javax.swing.JPanel
         private javax.swing.JPanel getJPanel1() {
              if(jPanel1 == null) {
                   jPanel1 = new javax.swing.JPanel();
                   java.awt.GridLayout layGridLayout2 = new java.awt.GridLayout();
                   layGridLayout2.setRows(2);
                   layGridLayout2.setColumns(1);
                   jPanel1.setLayout(layGridLayout2);
                   jPanel1.add(getJLabel2(), null);
                   jPanel1.add(getJLabel1(), null);
              return jPanel1;
         * This method initializes jLabel1
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel1() {
              if(jLabel1 == null) {
                   jLabel1 = new javax.swing.JLabel();
                   jLabel1.setText("one");
              return jLabel1;
         * This method initializes jLabel2
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel2() {
              if(jLabel2 == null) {
                   jLabel2 = new javax.swing.JLabel();
                   jLabel2.setText("one");
              return jLabel2;
    import javax.swing.*;
    public class Two extends JPanel {
         private javax.swing.JLabel jLabel = null;
         public Two() {
              super();
              initialize();
         * This method initializes this
         * @return void
         private void initialize() {
              this.setLayout(new java.awt.FlowLayout());
              this.add(getJLabel(), null);
              this.setSize(300, 200);
         * This method initializes jLabel
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel() {
              if(jLabel == null) {
                   jLabel = new javax.swing.JLabel();
                   jLabel.setText("two");
              return jLabel;
    }

    //change.repaint();
    change.revalidate();

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Problem with JInternalFrame

    Hii there,
    I'm having a problem with JInternalFrame, that is, when I'm trying to open multiple frames, it is overlapping one another and sometimes one of them disappears, I did something like this,
    dpane=new JDesktopPane();                                                 
                            dpane.setDesktopManager(new DefaultDesktopManager());
                            dpane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
                            iframe=new JInternalFrame("Title" ,true,true,true,true);  
                            //iframe.setPreferredSize(new Dimension(1010,800));
                            iframe.setResizable(false);
                            vScrollPane = new JScrollPane(viewPanel,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                       
                            iframe.setPreferredSize(new Dimension(1010,800));
                            iframe.setLocation(0,1);
                            iframe.setVisible(true);
                            iframe.show();
                            iframe.getContentPane().add(vScrollPane,BorderLayout.EAST);                      
                            iframe.getContentPane().add(hScrollBar,BorderLayout.SOUTH);
                            iframe.moveToFront();
                            iframe.setFocusable(true);
                            iframe.pack();
                            dpane.add(iframe);                                      
                            getContentPane().add(dpane);could u someone plz help me !
    Dev

    [How to Use Internal Frames|http://java.sun.com/docs/books/tutorial/uiswing/components/internalframe.html]

  • Design problem with JScrollPane

    First, I have problems with english. I hope u understand without problems that Im trying to say here. Sorry about that.
    Mi problem is whit a JScrollPane. I want to put an image whit a predefined size for draw inside it. I dont have any information about it, just the size. I want to put it in a JPane. The best choice is use the JPane area. The problem is that I want to use a JScrollPane because the image is bigger that the visualization area.
    Im unable to put a Canvas in the ScrollPane, or a JPane whit a predefined size or an image whit a predefined size. Im sure that is a design problem. Somebody can tell me something I can start whit? What do u think is better choice to put inside a JScrollPane?
    I dont send any source code because I dont have anything else that is show in the example.
    Gracias.

    import java.awt.*;
    import javax.swing.*;
    import java.net.URL;
    public class Test extends JFrame {
      String url = "http://www.sandbox-usa.com/images/product_images/2piece_16.gif";
      public Test() {
    //    System.getProperties().put( "proxySet", "true" );  // uncomment if you have proxy
    //    System.getProperties().put( "proxyHost", "myproxy.mydomain.com" ); // Your proxyname/IP
    //    System.getProperties().put( "proxyPort", "80"); // Sometimes 8080   
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
        Container content = getContentPane();
        try {
          Image i = Toolkit.getDefaultToolkit().getImage(new URL(url));
          JLabel jl = new JLabel(new ImageIcon(i));
          content.add(new JScrollPane(jl), BorderLayout.CENTER);
          setSize(200, 200);   
          setVisible(true); 
        } catch (Exception e) { e.printStackTrace(); }
      public static void main(String[] args) { new Test(); }
    }

  • Problem with writing and reading using serialization

    I am having a problem with writing and reading an object that has another object in it. The purpose of the class is to write a order that has multiple items in it. And there will be several orders. This is for an IB project, where one of the requirements is to utilize a hierarchical composite data structure. That is, it is "one that contains more than one element and at least one of the elements is a composite data structure. Examples are, an array or linked list of records, a record that has one field that is another record, or an array". The code is shown below:
    The error produced is
    java.lang.NullPointerException
         at SamsonRubberIndustries.CustomerOrderDetails.createCustOrdDetailsScreen(CustomerOrderDetails.java:150)
         at SamsonRubberIndustries.CustomerOrderDetails$1.run(CustomerOrderDetails.java:78)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    public class CustOrdObject implements Serializable {
         public int CustID;
         public int CustOrderID;
         public Object OrderDate;
         public InnerCustOrdObject[] innerCustOrdObj;
         public float GrandTotal;
         public int MaxItems;
         public CustOrdObject() {}
         public CustOrdObject(InnerCustOrdObject[] innerCustOrdObj,
    int CustID, int CustOrderID, Object OrderDate,
    float GrandTotal, int innerarrlength, int innerarrpos, int MaxItems) {
              this.CustID = CustID;
              this.CustOrderID = CustOrderID;
              this.OrderDate = OrderDate;
              this.GrandTotal = GrandTotal;          
              this.MaxItems = MaxItems;
              this.innerCustOrdObj = new InnerCustOrdObject[MaxItems];
         public InnerCustOrdObject[] getInnerCustOrdObj() {
              return innerCustOrdObj;
         public void setInnerCustOrdObj(InnerCustOrdObject[] innerCustOrdObj) {
              this.innerCustOrdObj = innerCustOrdObj;
         public int getCustID() {
              return CustID;
         public void setCustID(int custID) {
              CustID = custID;
         public int getCustOrderID() {
              return CustOrderID;
         public void setCustOrderID(int custOrderID) {
              CustOrderID = custOrderID;
         public Object getOrderDate() {
              return OrderDate;
         public void setOrderDate(Object orderDate) {
              OrderDate = orderDate;
         public void setGrandTotal(float grandTotal) {
              GrandTotal = grandTotal;
         public float getGrandTotal() {
              return GrandTotal;
         public int getMaxItems() {
              return MaxItems;
         public void setMaxItems(int maxItems) {
              MaxItems = maxItems;
    public class InnerCustOrdObject implements Serializable{
         public int ItemNumber;
         public float UnitPrice;
         public int QuantityRequired;
         public float TotalPrice;
         public InnerCustOrdObject() {}
         public InnerCustOrdObject(int ItemNumber, float
    UnitPrice, int QuantityRequired, float TotalPrice){
              this.ItemNumber = ItemNumber;
              this.UnitPrice = UnitPrice;
              this.QuantityRequired = QuantityRequired;
              this.TotalPrice = TotalPrice;
         public int getItemNumber() {
              return ItemNumber;
         public void setItemNumber(int itemNumber) {
              ItemNumber = itemNumber;
         public int getQuantityRequired() {
              return QuantityRequired;
         public void setQuantityRequired(int quantityRequired) {
              QuantityRequired = quantityRequired;
         public float getTotalPrice() {
              return TotalPrice;
         public void setTotalPrice(float totalPrice) {
              TotalPrice = totalPrice;
         public float getUnitPrice() {
              return UnitPrice;
         public void setUnitPrice(float unitPrice) {
              UnitPrice = unitPrice;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.swing.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    public class CustomerOrderDetails extends CommonFeatures{
         //TODO
         private static int MAX_ORDERS = 200;
         private static int MAX_ORDERITEMS = 100;
         private static int MaxRecord;
         private static int CurrentRecord = 1;
         private static int currentItem;
         private static int MaxItems;
         private static boolean FileExists, recFileExists;
         private static CustOrdObject[] orderDetails = new CustOrdObject[MAX_ORDERS];
         private static InnerCustOrdObject[] innerCustOrdObj = new InnerCustOrdObject[MAX_ORDERITEMS];     
         private static File OrderDetailsFile = new File("CustOrdDetails.dat");
         private static File OrdRecordNumStore = new File("OrdRecordNumStore.txt");
         private static PrintWriter writeFile;
         private static BufferedReader readFile;
         private static ObjectOutputStream objOut;
         private static ObjectInputStream objIn;
         //Set format for date
         SimpleDateFormat simpleDF = new SimpleDateFormat("dd MM yyyy");
         //--<BEGINNING>--Declaring Interface Variables------------------------------------------//
         private JPanel innertoppanel, innercenterpanel, innerbottompanel, innerrightpanel, innerleftpanel;
         private JLabel CustIDLbl, CustOrderIDLbl, OrderedDateLbl, GrandTotLbl, ItemNumberLbl,UnitPriceLbl, QuantityReqLbl, TotPriceLbl;
         private JTextField CustIDTxt, CustOrderIDTxt, OrderedDateTxt, GrandTotTxt, ItemNumberTxt, UnitPriceTxt, QuantityReqTxt, TotPriceTxt;
         private JButton addrecordbtn, savebtn, externalprevbtn, externalnextbtn, internalprevbtn, internalnextbtn, gotorecordbtn, additemreqbtn;
         //--<END>--Declaring Interface Variables------------------------------------------------//
         public static void main(String[] args) {
              final CustomerOrderDetails COD = new CustomerOrderDetails();
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                             COD.createCustOrdDetailsScreen();
                        } catch (Exception eb) {
                             eb.printStackTrace();
         //--<BEGINNING>--Creating CustomerOrderDetails Screen---------------------------------------//
         public JFrame createCustOrdDetailsScreen() {
              createDefaultFrame();
              mainframe.setSize(800,500);
              createContainerPanel();
              containerpanel.add(createCustOrdDetailsTitle(), BorderLayout.NORTH);
              containerpanel.add(createCustOrdDetailsMainPanel(), BorderLayout.CENTER);
              //containerpanel.add(createCustOrdDetailsLeftNavButtons(), BorderLayout.WEST);
              //containerpanel.add(createCustOrdDetailsRightNavButtons(), BorderLayout.EAST);
              containerpanel.add(createCustOrdDetailsButtons(), BorderLayout.SOUTH);
              mainframe.setContentPane(containerpanel);
              mainframe.setLocationRelativeTo(null);
              mainframe.setVisible(true);
              //--<BEGINNING>--Checks to see whether CRecordNumberStore file exists-------------------------------//
              if (OrdRecordNumStore.exists() == true) {
                   recFileExists = true;
              }else {
                   recFileExists = false;
              if (recFileExists == true) {
                   MaxRecord = readRecordNumber();
                   CurrentRecord = MaxRecord;
                   //readOrder();
                   //readInnerOrderRecord(CurrentRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              }else{
                   MaxRecord = 1;
                   writeRecordNumber(MaxRecord);
                   CustOrderIDTxt.setText(""+MaxRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              //--<END>--Checks to see whether CRecordNumberStore file exists--------------------------------------//
              if(readOrder() != null){
                   orderDetails = (CustOrdObject[]) readOrder();
                 innerCustOrdObj = orderDetails[CurrentRecord].getInnerCustOrdObj();
                   MaxItems = orderDetails[CurrentRecord].getMaxItems();
                   if(CurrentRecord > 1 && CurrentRecord < MaxRecord){
                        externalnextbtn.setEnabled(true);
                        externalprevbtn.setEnabled(true);
                   if(CurrentRecord >= MaxRecord){
                        externalnextbtn.setEnabled(false);
                   getFieldText(CurrentRecord-1);
              }else{
                   orderDetails[CurrentRecord] = new CustOrdObject();
                   currentItem = 1;
              return mainframe;
         //--<END>--Creating CustomerOrderDetails Screen---------------------------------------------//
         public JPanel createCustOrdDetailsTitle(){
              createTitlePanel();
              titlepanel.setBackground(TxtfontColor);
              label.setText("- Customer Order Details -");
              labelpanel.setBackground(TxtfontColor);
              label.setForeground(Color.white);
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor) ;
              buttonpanel.add(createReturnToMainMenuButton());
              titlepanel.add(labelpanel, BorderLayout.WEST);
              titlepanel.add(buttonpanel, BorderLayout.EAST);
              return titlepanel;
         public JPanel createCustOrdDetailsMainPanel(){
              createmainpanel();
              mainpanel.setBackground(TxtfontColor);
              mainpanel.setLayout(new BorderLayout());          
              mainpanel.setBorder(BorderFactory.createTitledBorder(""));
              mainpanel.add(createInnerTopPanel(), BorderLayout.NORTH);
              mainpanel.add(createInnerCenterPanel(), BorderLayout.CENTER);
              mainpanel.add(createInnerBottomPanel(), BorderLayout.SOUTH);
              mainpanel.add(createInnerRightPanel(), BorderLayout.EAST);
              mainpanel.add(createInnerLeftPanel(), BorderLayout.WEST);
              return mainpanel;
         public JPanel createInnerTopPanel(){
              innertoppanel = new JPanel(new GridBagLayout());
              innertoppanel.setBackground(TxtfontColor);
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              CustIDLbl = new JLabel("Customer ID");
              CustIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustIDLbl.setFont(font);
              CustIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innertoppanel.add(CustIDLbl, GBC);     
              CustIDTxt = new JTextField(20);
              CustIDTxt.setEditable(true);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innertoppanel.add(CustIDTxt, GBC);
              GBC.gridx = 3;
              GBC.gridy = 1;
              innertoppanel.add(Box.createHorizontalStrut(220), GBC);
              OrderedDateLbl = new JLabel("Order Date");
              OrderedDateLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              OrderedDateLbl.setFont(font);
              OrderedDateLbl.setForeground(LblfontColor);
              GBC.gridx = 4;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateLbl, GBC);     
              //Get today's date
              Date todaydate = new Date();
              OrderedDateTxt = new JTextField(simpleDF.format(todaydate), 20);
              OrderedDateTxt.setHorizontalAlignment(JTextField.CENTER);
              OrderedDateTxt.setEditable(false);
              GBC.gridx = 5;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateTxt, GBC);
              CustOrderIDLbl = new JLabel("Customer Order ID");
              CustOrderIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustOrderIDLbl.setFont(font);
              CustOrderIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDLbl, GBC);
              CustOrderIDTxt = new JTextField(20);
              CustOrderIDTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDTxt, GBC);
              return innertoppanel;
         public JPanel createInnerCenterPanel(){
              innercenterpanel = new JPanel(new GridBagLayout());
              innercenterpanel.setBackground(TxtfontColor);
              innercenterpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              ItemNumberLbl = new JLabel("Item Number");
              ItemNumberLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              ItemNumberLbl.setFont(font);
              ItemNumberLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberLbl, GBC);     
              ItemNumberTxt = new JTextField(20);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberTxt, GBC);
              UnitPriceLbl = new JLabel("Unit Price");
              UnitPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              UnitPriceLbl.setFont(font);
              UnitPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceLbl, GBC);     
              UnitPriceTxt = new JTextField(20);
              //UnitPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceTxt, GBC);
              QuantityReqLbl = new JLabel("Quantity Required");
              QuantityReqLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              QuantityReqLbl.setFont(font);
              QuantityReqLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqLbl, GBC);     
              QuantityReqTxt = new JTextField(20);
              //QuantityReqTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqTxt, GBC);
              TotPriceLbl = new JLabel("Total Price");
              TotPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              TotPriceLbl.setFont(font);
              TotPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceLbl, GBC);     
              TotPriceTxt = new JTextField(20);
              //TotPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceTxt, GBC);
              return innercenterpanel;
         public JPanel createInnerBottomPanel(){
              innerbottompanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              innerbottompanel.setBackground(TxtfontColor);
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              GrandTotLbl = new JLabel("Grand Total");
              GrandTotLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              GrandTotLbl.setFont(font);
              GrandTotLbl.setForeground(LblfontColor);
              innerbottompanel.add(GrandTotLbl);
              innerbottompanel.add(Box.createHorizontalStrut(30));
              GrandTotTxt = new JTextField(20);
              innerbottompanel.add(GrandTotTxt);
              return innerbottompanel;
         public JPanel createInnerRightPanel(){
              innerrightpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerrightpanel.setBackground(TxtfontColor);
              innerrightpanel.setLayout(new BoxLayout(navrightpanel, BoxLayout.Y_AXIS));
              innerrightpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerrightpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalnextbtn = new JButton(createNextButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        //getInnerFieldText(currentItem);
                        internalprevbtn.setEnabled(true);
                        if(currentItem < MaxItems){
                             ++CurrentRecord;
                             //readOrder();
                             //readInnerOrderRecord(CurrentRecord);
                             setInnerFieldText(currentItem);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(currentItem == MaxItems){
                             internalnextbtn.setEnabled(false);
              innerrightpanel.add(internalnextbtn, GBC);
              return innerrightpanel;
         public JPanel createInnerLeftPanel(){
              innerleftpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerleftpanel.setBackground(TxtfontColor);
              innerleftpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerleftpanel.setForeground(Color.BLACK);
              innerleftpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalprevbtn = new JButton(createPreviousButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        //getInnerFieldText(currentItem);
                        internalnextbtn.setEnabled(true);
                        if(currentItem == 1){
                             internalprevbtn.setEnabled(false);
                        if(currentItem > 0){
                             --currentItem;
                             //readOrder();
                             setInnerFieldText(currentItem);
              innerleftpanel.add(internalprevbtn, GBC);
              return innerleftpanel;
         public JPanel createCustOrdDetailsButtons(){
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor);
              externalprevbtn = new JButton(createPreviousButtonIcon());
              externalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalnextbtn.setEnabled(true);
                        if(CurrentRecord == 1){
                             externalprevbtn.setEnabled(false);
                        if(CurrentRecord > 0){
                             --CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
              buttonpanel.add(externalprevbtn);
              addrecordbtn = new JButton("Add Record", createAddButtonIcon());
              addrecordbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             MaxRecord = readRecordNumber();
                             MaxRecord++;
                             writeRecordNumber(MaxRecord);
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             CustIDTxt.setText("");
                             CustOrderIDTxt.setText(""+MaxRecord);
                             //Get today's date
                             Date todaydate = new Date();
                             OrderedDateTxt.setText(""+simpleDF.format(todaydate));
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             GrandTotTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             externalnextbtn.setEnabled(false);
                             externalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(addrecordbtn);
              savebtn = new JButton("Save Data", createSaveButtonIcon());
              savebtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        setFieldText(CurrentRecord);
                        writeOrder();
                        writeRecordNumber(MaxRecord);
                        System.out.println(CurrentRecord);
                        System.out.println(MaxRecord);
              buttonpanel.add(savebtn);
              java.net.URL imageURL_AddRowIcon = CommonFeatures.class.getResource("Icons/edit_add.png");
              ImageIcon AddRowIcon = new ImageIcon(imageURL_AddRowIcon);
              additemreqbtn = new JButton("Add Item", AddRowIcon);
              additemreqbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             //CurrentRecord = MaxRecord;
                             currentItem++;
                             setInnerFieldText(currentItem);
                             internalnextbtn.setEnabled(false);
                             internalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(additemreqbtn);
              externalnextbtn = new JButton(createNextButtonIcon());
              externalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalprevbtn.setEnabled(true);
                        if(CurrentRecord < MaxRecord){
                             ++CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(CurrentRecord == MaxRecord){
                             externalnextbtn.setEnabled(false);
              buttonpanel.add(externalnextbtn);
              return buttonpanel;
         //TODO
         public void setFieldText(int orderID){//TODO
              orderDetails[orderID].setCustID(Integer.parseInt(CustIDTxt.getText()));
              orderDetails[orderID].setCustOrderID(Integer.parseInt(CustOrderIDTxt.getText()));
              orderDetails[orderID].setOrderDate(OrderedDateTxt.getText());
              orderDetails[orderID].setInnerCustOrdObj(innerCustOrdObj);
              orderDetails[orderID].setMaxItems(MaxItems);
              setInnerFieldText(currentItem);
              orderDetails[orderID].setGrandTotal(Float.parseFloat(GrandTotTxt.getText()));
         public void setInnerFieldText(int currentItem){//TODO
              innerCustOrdObj[currentItem] = new InnerCustOrdObject();
              innerCustOrdObj[currentItem].setItemNumber(Integer.parseInt(ItemNumberTxt.getText()));
              innerCustOrdObj[currentItem].setUnitPrice(Float.parseFloat(UnitPriceTxt.getText()));
              innerCustOrdObj[currentItem].setQuantityRequired(Integer.parseInt(QuantityReqTxt.getText()));
              innerCustOrdObj[currentItem].setTotalPrice(Float.parseFloat(TotPriceTxt.getText()));
         public void getFieldText(int orderID){
              CustIDTxt.setText(Integer.toString(orderDetails[orderID].getCustID()));
              CustOrderIDTxt.setText(Integer.toString(orderDetails[orderID].getCustOrderID()));
              OrderedDateTxt.setText(""+orderDetails[orderID].getOrderDate());          
              currentItem = orderDetails[orderID].getMaxItems();
              System.err.println("currentItem" + currentItem);
              getInnerFieldText(currentItem);
              GrandTotTxt.setText(Float.toString(orderDetails[orderID].getGrandTotal()));
         public void getInnerFieldText(int currentItem){
              ItemNumberTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getItemNumber()));
              UnitPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getUnitPrice()));
              QuantityReqTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getQuantityRequired()));
              TotPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getTotalPrice()));
         public void writeOrder(){//TODO
              try {
                   objOut = new ObjectOutputStream(new FileOutputStream(OrderDetailsFile));
                   objOut.writeObject(orderDetails);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              } catch (IOException e) {
                   e.printStackTrace();
         public Object readOrder(){
              Object temporaryObj;
              try{
                   objIn = new ObjectInputStream(new FileInputStream(OrderDetailsFile));
                   temporaryObj = objIn.readObject();               
                   CustOrdObject[] blah = (CustOrdObject[]) temporaryObj;
                   System.out.println("Outer: "+blah[1].getCustID());
                   InnerCustOrdObject[] whee = blah[1].getInnerCustOrdObj();
                   System.out.println("Inner: "+whee[1].getItemNumber());
                   objIn.close();
                   System.out.println("Read Worky!");
                   return temporaryObj;
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println("Read No Worky!");
                   return null;
         public void writeRecordNumber(int MaxRecord){
              try{
                   objOut = new ObjectOutputStream(new FileOutputStream(OrdRecordNumStore));
                   objOut.writeObject(MaxRecord);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              }catch(Exception e){e.printStackTrace();}
         public int readRecordNumber() {
              try {
                   objIn = new ObjectInputStream(new FileInputStream(OrdRecordNumStore));
                   int temporaryObj = Integer.parseInt(objIn.readObject().toString());
                   objIn.close();
                   System.out.println("Read Number Worky!");
                   return temporaryObj;
              } catch (Exception e) {
                   e.printStackTrace();
                   System.out.println("Read Number No Worky!");
                   return -1;
    }Message was edited by:
    Kilik07
    Message was edited by:
    Kilik07

    ok i got reading to work to a certain extent... but the prob is i cnt seem to save my innerCustOrdObj proprly...when ever i look for a record using the gotorecordbtn, the outerobject, which is the orderDetails, seems to change but the innerCustOrdObj remains the same... heres the new code..
    public class CustomerOrderDetails extends CommonFeatures{
         //TODO
         private static int MAX_ORDERS = 200;
         private static int MAX_ORDERITEMS = 100;
         private static int MaxRecord;
         private static int CurrentRecord = 1;
         private static int currentItem;
         private static int MaxItems = 1;
         private static boolean FileExists, recFileExists;
         private static boolean RecordExists;
         private static CustOrdObject[] orderDetails = new CustOrdObject[MAX_ORDERS];
         private static InnerCustOrdObject[] innerCustOrdObj = new InnerCustOrdObject[MAX_ORDERITEMS];     
         private static File OrderDetailsFile = new File("CustOrdDetails.ser");
         private static File OrdRecordNumStore = new File("OrdRecordNumStore.txt");
         private static PrintWriter writeFile;
         private static BufferedReader readFile;
         private static ObjectOutputStream objOut;
         private static ObjectInputStream objIn;
         //Set format for date
         SimpleDateFormat simpleDF = new SimpleDateFormat("dd MM yyyy");
         //--<BEGINNING>--Declaring Interface Variables------------------------------------------//
         private JPanel innertoppanel, innercenterpanel, innerbottompanel, innerrightpanel, innerleftpanel;
         private JLabel CustIDLbl, CustOrderIDLbl, OrderedDateLbl, GrandTotLbl, ItemNumberLbl,UnitPriceLbl, QuantityReqLbl, TotPriceLbl;
         private JTextField CustIDTxt, CustOrderIDTxt, OrderedDateTxt, GrandTotTxt, ItemNumberTxt, UnitPriceTxt, QuantityReqTxt, TotPriceTxt;
         private JButton addrecordbtn, savebtn, externalprevbtn, externalnextbtn, internalprevbtn, internalnextbtn, gotorecordbtn, additemreqbtn;
         //--<END>--Declaring Interface Variables------------------------------------------------//
         public static void main(String[] args) {
              final CustomerOrderDetails COD = new CustomerOrderDetails();
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                             COD.createCustOrdDetailsScreen();
                        } catch (Exception eb) {
                             eb.printStackTrace();
         //--<BEGINNING>--Creating CustomerOrderDetails Screen---------------------------------------//
         public JFrame createCustOrdDetailsScreen() {
              createDefaultFrame();
              mainframe.setSize(800,500);
              createContainerPanel();
              containerpanel.add(createCustOrdDetailsTitle(), BorderLayout.NORTH);
              containerpanel.add(createCustOrdDetailsMainPanel(), BorderLayout.CENTER);
              //containerpanel.add(createCustOrdDetailsLeftNavButtons(), BorderLayout.WEST);
              //containerpanel.add(createCustOrdDetailsRightNavButtons(), BorderLayout.EAST);
              containerpanel.add(createCustOrdDetailsButtons(), BorderLayout.SOUTH);
              mainframe.setContentPane(containerpanel);
              mainframe.setLocationRelativeTo(null);
              mainframe.setVisible(true);
              //--<BEGINNING>--Checks to see whether CRecordNumberStore file exists-------------------------------//
              if (OrdRecordNumStore.exists() == true) {
                   recFileExists = true;
              }else {
                   recFileExists = false;
              if (recFileExists == true) {
                   MaxRecord = readRecordNumber();
                   CurrentRecord = MaxRecord;
                   //readOrder();
                   //readInnerOrderRecord(CurrentRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              }else{
                   MaxRecord = 1;
                   writeRecordNumber(MaxRecord);
                   CustOrderIDTxt.setText(""+MaxRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              //--<END>--Checks to see whether CRecordNumberStore file exists--------------------------------------//
              if(readOrder() != null){
                   orderDetails = (CustOrdObject[]) readOrder();
                   //CurrentRecord--;
                   //System.out.println("Current Rec Here"+CurrentRecord);
                   if(orderDetails[CurrentRecord] == null){
                        System.err.println("CustomerOrderObj 1 is null !!");
                   }else{
                        System.err.println("CustomerOrderObj 1 is  not null !!");
                   if(orderDetails[CurrentRecord].getInnerCustOrdObj() == null){
                        System.err.println("InnerCustomerOrderObj is null !!");
                   }else{
                        System.err.println("InnerCustomerOrderObj is  not null !!");
                   innerCustOrdObj = orderDetails[CurrentRecord].getInnerCustOrdObj();
                   MaxItems = orderDetails[CurrentRecord].getMaxItems();
                   if(CurrentRecord > 1 && CurrentRecord < MaxRecord){
                        externalnextbtn.setEnabled(true);
                        externalprevbtn.setEnabled(true);
                   if(CurrentRecord >= MaxRecord){
                        externalnextbtn.setEnabled(false);
                   getFieldText(CurrentRecord);
                   getInnerFieldText(MaxItems);
              }else{
                   orderDetails[CurrentRecord] = new CustOrdObject();
                   currentItem = 1;
              return mainframe;
         //--<END>--Creating CustomerOrderDetails Screen---------------------------------------------//
         public JPanel createCustOrdDetailsTitle(){
              createTitlePanel();
              titlepanel.setBackground(TxtfontColor);
              label.setText("- Customer Order Details -");
              labelpanel.setBackground(TxtfontColor);
              label.setForeground(Color.white);
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor) ;
              buttonpanel.add(createReturnToMainMenuButton());
              titlepanel.add(labelpanel, BorderLayout.WEST);
              titlepanel.add(buttonpanel, BorderLayout.EAST);
              return titlepanel;
         public JPanel createCustOrdDetailsMainPanel(){
              createmainpanel();
              mainpanel.setBackground(TxtfontColor);
              mainpanel.setLayout(new BorderLayout());          
              mainpanel.setBorder(BorderFactory.createTitledBorder(""));
              mainpanel.add(createInnerTopPanel(), BorderLayout.NORTH);
              mainpanel.add(createInnerCenterPanel(), BorderLayout.CENTER);
              mainpanel.add(createInnerBottomPanel(), BorderLayout.SOUTH);
              mainpanel.add(createInnerRightPanel(), BorderLayout.EAST);
              mainpanel.add(createInnerLeftPanel(), BorderLayout.WEST);
              return mainpanel;
         public JPanel createInnerTopPanel(){
              innertoppanel = new JPanel(new GridBagLayout());
              innertoppanel.setBackground(TxtfontColor);
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              CustIDLbl = new JLabel("Customer ID");
              CustIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustIDLbl.setFont(font);
              CustIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innertoppanel.add(CustIDLbl, GBC);     
              CustIDTxt = new JTextField(20);
              CustIDTxt.setEditable(true);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innertoppanel.add(CustIDTxt, GBC);
              GBC.gridx = 3;
              GBC.gridy = 1;
              innertoppanel.add(Box.createHorizontalStrut(220), GBC);
              OrderedDateLbl = new JLabel("Order Date");
              OrderedDateLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              OrderedDateLbl.setFont(font);
              OrderedDateLbl.setForeground(LblfontColor);
              GBC.gridx = 4;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateLbl, GBC);     
              //Get today's date
              Date todaydate = new Date();
              OrderedDateTxt = new JTextField(simpleDF.format(todaydate), 20);
              OrderedDateTxt.setHorizontalAlignment(JTextField.CENTER);
              OrderedDateTxt.setEditable(false);
              GBC.gridx = 5;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateTxt, GBC);
              CustOrderIDLbl = new JLabel("Customer Order ID");
              CustOrderIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustOrderIDLbl.setFont(font);
              CustOrderIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDLbl, GBC);
              CustOrderIDTxt = new JTextField(20);
              //CustOrderIDTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDTxt, GBC);
              return innertoppanel;
         public JPanel createInnerCenterPanel(){
              innercenterpanel = new JPanel(new GridBagLayout());
              innercenterpanel.setBackground(TxtfontColor);
              innercenterpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              ItemNumberLbl = new JLabel("Item Number");
              ItemNumberLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              ItemNumberLbl.setFont(font);
              ItemNumberLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberLbl, GBC);     
              ItemNumberTxt = new JTextField(20);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberTxt, GBC);
              UnitPriceLbl = new JLabel("Unit Price");
              UnitPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              UnitPriceLbl.setFont(font);
              UnitPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceLbl, GBC);     
              UnitPriceTxt = new JTextField(20);
              //UnitPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceTxt, GBC);
              QuantityReqLbl = new JLabel("Quantity Required");
              QuantityReqLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              QuantityReqLbl.setFont(font);
              QuantityReqLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqLbl, GBC);     
              QuantityReqTxt = new JTextField(20);
              //QuantityReqTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqTxt, GBC);
              TotPriceLbl = new JLabel("Total Price");
              TotPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              TotPriceLbl.setFont(font);
              TotPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceLbl, GBC);     
              TotPriceTxt = new JTextField(20);
              TotPriceTxt.setEditable(false);
              TotPriceTxt.addFocusListener(new FocusAdapter(){
                   public void focusGained(FocusEvent evt){
                        TotPriceTxt.setText(""+Integer.parseInt(UnitPriceTxt.getText())*Integer.parseInt(QuantityReqTxt.getText()));
              GBC.gridx = 2;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceTxt, GBC);
              return innercenterpanel;
         public JPanel createInnerBottomPanel(){
              innerbottompanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              innerbottompanel.setBackground(TxtfontColor);
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              GrandTotLbl = new JLabel("Grand Total");
              GrandTotLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              GrandTotLbl.setFont(font);
              GrandTotLbl.setForeground(LblfontColor);
              innerbottompanel.add(GrandTotLbl);
              innerbottompanel.add(Box.createHorizontalStrut(30));
              GrandTotTxt = new JTextField(20);
              innerbottompanel.add(GrandTotTxt);
              return innerbottompanel;
         public JPanel createInnerRightPanel(){
              innerrightpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerrightpanel.setBackground(TxtfontColor);
              innerrightpanel.setLayout(new BoxLayout(navrightpanel, BoxLayout.Y_AXIS));
              innerrightpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerrightpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalnextbtn = new JButton(createNextButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getInnerFieldText(currentItem);
                        internalprevbtn.setEnabled(true);
                        if(currentItem < MaxItems){
                             ++currentItem;
                             orderDetails[CurrentRecord].getInnerCustOrdObj();
                             setInnerFieldText(currentItem);
                             System.out.println("Current Item" + currentItem);
                        if(currentItem == MaxItems){
                             internalnextbtn.setEnabled(false);
              innerrightpanel.add(internalnextbtn, GBC);
              return innerrightpanel;
         public JPanel createInnerLeftPanel(){
              innerleftpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerleftpanel.setBackground(TxtfontColor);
              innerleftpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerleftpanel.setForeground(Color.BLACK);
              innerleftpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalprevbtn = new JButton(createPreviousButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getInnerFieldText(currentItem);
                        internalnextbtn.setEnabled(true);
                        if(currentItem == 1){
                             internalprevbtn.setEnabled(false);
                        if(currentItem > 0){
                             --currentItem;
                             orderDetails[CurrentRecord].getInnerCustOrdObj();
                             setInnerFieldText(currentItem);
                             System.out.println("Current Item" + currentItem);
              innerleftpanel.add(internalprevbtn, GBC);
              return innerleftpanel;
         public JPanel createCustOrdDetailsButtons(){
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor);
              externalprevbtn = new JButton(createPreviousButtonIcon());
              externalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalnextbtn.setEnabled(true);
                        if(CurrentRecord == 1){
                             externalprevbtn.setEnabled(false);
                        if(CurrentRecord > 0){
                             --CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println("Current Record " + CurrentRecord);//Checking RECORD_NUM
              buttonpanel.add(externalprevbtn);
              addrecordbtn = new JButton("Add Record", createAddButtonIcon());
              addrecordbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             MaxRecord = readRecordNumber();
                             MaxRecord++;
                             CurrentRecord = MaxRecord;
                             orderDetails[CurrentRecord] = new CustOrdObject();
                             writeRecordNumber(MaxRecord);
                             MaxItems = 1;
                             innerCustOrdObj[MaxItems] = new InnerCustOrdObject();
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             CustIDTxt.setText("");
                             CustOrderIDTxt.setText(""+MaxRecord);
                             //Get today's date
                             Date todaydate = new Date();
                             OrderedDateTxt.setText(""+simpleDF.format(todaydate));
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             GrandTotTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             externalnextbtn.setEnabled(false);
                             externalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(addrecordbtn);
              savebtn = new JButton("Save Data", createSaveButtonIcon());
              savebtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        setFieldText(CurrentRecord);
                        setInnerFieldText(MaxItems);
                        writeOrder();
                        writeRecordNumber(MaxRecord);
                        System.out.println(CurrentRecord);
                        System.out.println(MaxRecord);
              buttonpanel.add(savebtn);
              java.net.URL imageURL_AddRowIcon = CommonFeatures.class.getResource("Icons/edit_add.png");
              ImageIcon AddRowIcon = new ImageIcon(imageURL_AddRowIcon);
              additemreqbtn = new JButton("Add Item", AddRowIcon);
              additemreqbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             //CurrentRecord = MaxRecord;
                             MaxItems++;
                             innerCustOrdObj[MaxItems] = new InnerCustOrdObject();
                             System.out.println("Max Items "+MaxItems);
                             currentItem = MaxItems;
                             orderDetails[CurrentRecord].setMaxItems(MaxItems);
                             ///setInnerFieldText(currentItem);
                             internalnextbtn.setEnabled(false);
                             internalprevbtn.setEnabled(true);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(additemreqbtn);
              externalnextbtn = new JButton(createNextButtonIcon());
              externalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalprevbtn.setEnabled(true);
                        if(CurrentRecord < MaxRecord){
                             ++CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(CurrentRecord == MaxRecord){
                             externalnextbtn.setEnabled(false);
              buttonpanel.add(externalnextbtn);
              gotorecordbtn = new JButton("Go To Record", createGotoButtonIcon());
              gotorecordbtn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt){
                         * The text from the GotorecordTxt textfield will be taken and assigned
                         * to a temporary integer variable called Find. 
                        int Find = Integer.parseInt(CustOrderIDTxt.getText());
                        for(int j=1; j <= MaxRecord; j++){
                              * Using a for loop, each record can be read using the readCustRecord
                              * method.
                             getFieldText(j);
                              * An if condition is utilized to check whether the temporary stored variable, Find,
                              * matches a field in a record. If this record is found, then using the RecordExists
                              * which was declared at the top, either a true or false statement can be assigned
                              * If the record exists, then a true statement will be assigned, if not a false
                              * statement will be assigned.
                             if(orderDetails[j].getCustOrderID() == Find){
                                  RecordExists = true;
                                  break;
                             }else{
                                  RecordExists = false;
                        if(RecordExists == false){
                              * If the RecordExists is assigned a false statement, then a message will be
                              * displayed to show that the record does not exist.
                             JOptionPane.showMessageDialog(null, "Record Does Not Exist!", "Error Message", JOptionPane.ERROR_MESSAGE, createErrorIcon());
                        }else{
                             getFieldText(Find);
              buttonpanel.add(gotorecordbtn);
              return buttonpanel;
         //TODO
         public void setFieldText(int orderID){//TODO
              orderDetails[orderID].setCustID(Integer.parseInt(CustIDTxt.getText()));
              orderDetails[orderID].setCustOrderID(Integer.parseInt(CustOrderIDTxt.getText()));
              orderDetails[orderID].setOrderDate(OrderedDateTxt.getText());
              orderDetails[orderID].setInnerCustOrdObj(innerCustOrdObj);
              orderDetails[orderID].setMaxItems(MaxItems);
              setInnerFieldText(currentItem);
              orderDetails[orderID].setGrandTotal(Float.parseFloat(GrandTotTxt.getText()));
         public void setInnerFieldText(int currentItem){//TODO
              innerCustOrdObj[currentItem] = new InnerCustOrdObject();
              innerCustOrdObj[currentItem].setMaxItems(MaxItems);
              innerCustOrdObj[currentItem].setItemNumber(Integer.parseInt(ItemNumberTxt.getText()));
              innerCustOrdObj[currentItem].setUnitPrice(Float.parseFloat(UnitPriceTxt.getText()));
              innerCustOrdObj[currentItem].setQuantityRequired(Integer.parseInt(QuantityReqTxt.getText()));
              innerCustOrdObj[currentItem].setTotalPrice(Float.parseFloat(TotPriceTxt.getText()));
         public void getFieldText(int orderID){
              CustIDTxt.setText(Integer.toString(orderDetails[orderID].getCustID()));
              CustOrderIDTxt.setText(Integer.toString(orderDetails[orderID].getCustOrderID()));
              OrderedDateTxt.setText(""+orderDetails[orderID].getOrderDate());          
              currentItem = orderDetails[orderID].getMaxItems();
              orderDetails[orderID].getInnerCustOrdObj();
              System.err.println("currentItem" + currentItem);
              //getInnerFieldText(currentItem);
              GrandTotTxt.setText(Float.toString(orderDetails[orderID].getGrandTotal()));
         public void getInnerFieldText(int currentItem){
              ItemNumberTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getItemNumber()));
              UnitPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getUnitPrice()));
              QuantityReqTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getQuantityRequired()));
              TotPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getTotalPrice()));
         public void writeOrder(){//TODO
              try {
                   objOut = new ObjectOutputStream(new FileOutputStream(OrderDetailsFile));
                   objOut.writeObject(orderDetails);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              } catch (IOException e) {
                   e.printStackTrace();
         public Object readOrder(){
              Object temporaryObj;
              try{
                   objIn = new ObjectInputStream(new FileInputStream(OrderDetailsFile));
                   temporaryObj = objIn.readObject();               
                   CustOrdObject[] blah = (CustOrdObject[]) temporaryObj;
                   /*               System.out.println("Outer: "+blah[1].getCustID());
                   InnerCustOrdObject[] whee = blah[1].getInnerCustOrdObj();
                   System.out.println("Inner: "+whee[1].getItemNumber());*/
                   objIn.close();
                   System.out.println("Read Worky!");
                   return temporaryObj;
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println("Read No Worky!");
                   return null;
         public void writeRecordNumber(int MaxRecord){
              try{
                   objOut = new ObjectOutputStream(new FileOutputStream(OrdRecordNumStore));
                   objOut.writeObject(MaxRecord);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              }catch(Exception e){e.printStackTrace();}
         public int readRecordNumber() {
              try {
                   objIn = new ObjectInputStream(new FileInputStream(OrdRecordNumStore));
                   int temporaryObj = Integer.parseInt(objIn.readObject().toString());
                   objIn.close();
                   System.out.println("Read Number Worky!");
                   return temporaryObj;
              } catch (Exception e) {
                   e.printStackTrace();
                   System.out.println("Read Number No Worky!");
                   return -1;
    }Message was edited by:
    Kilik07

  • Problem with JPanel.updateUI()

    Hello,
    i have a problem with updateUI(), here's a simple example what's wrong. just compile and run the following piece of code and look what happens after 2 seconds: the left panel will be decrease its width after calling updateUI(), but why? is it a bug of updateUI() or is it my fault?
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JPanel
            private JList m_list;
            private DefaultListModel m_listModel;
            private JPanel m_buttons;
            public static GridBagConstraints creategbc (int x, int y, int w, int h, int wx, int wy, int f)
                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridx = x;
                    gbc.gridy = y;
                    gbc.gridwidth = w;
                    gbc.gridheight = h;
                    gbc.weightx = wx;
                    gbc.weighty = wy;
                    gbc.fill = f;
                    gbc.insets = new Insets(5, 5, 5, 5); // kleinen Rahmen ziehen
                    return gbc;
            public Test ()
                    GridBagLayout gbl = new GridBagLayout();
                    setLayout(gbl);
                    GridBagConstraints gbc;
                    initButtons();
                    gbc = creategbc(0, 0, 1, 1, 20, 100, GridBagConstraints.NONE);
                    gbc.anchor = GridBagConstraints.NORTH;
                    gbl.setConstraints(m_buttons, gbc);
                    add(m_buttons);
                    initList();
                    JScrollPane sp = new JScrollPane(m_list);
                    gbc = creategbc(1, 0, 1, 1, 100, 100, GridBagConstraints.BOTH);
                    gbl.setConstraints(sp, gbc);
                    add(sp);
            public void addItem (String item)
                    m_listModel.addElement(item);
            public void initList ()
                    m_listModel = new DefaultListModel();
                    m_list = new JList(m_listModel);
            public void initButtons ()
                    m_buttons = new JPanel();
                    m_buttons.setLayout(new GridLayout(4, 1, 0, 20));
                    m_buttons.add(new JButton("Neu"));
                    m_buttons.add(new JButton("Bearbeiten"));
                    m_buttons.add(new JButton("L�schen"));
                    m_buttons.add(new JButton("Abfrage"));
            public static void main (String[] args)
                    JFrame f = new JFrame();
                    Test t = new Test();
                    f.setContentPane(t);
                    f.setSize(600, 450);
                    f.setVisible(true);
                    try
                            Thread.sleep(2000);
                    catch (Exception e)
                    t.addItem("Hallo");
                    t.updateUI();

    Hello,
    i have a problem with updateUI(), here's a simple
    example what's wrong. just compile and run the
    following piece of code and look what happens after 2
    seconds: the left panel will be decrease its width
    after calling updateUI(), but why? is it a bug of
    updateUI() or is it my fault?updateUI() its called when the L&F is changed, there is
    rarely a case when you need to call updateUI().
    Why do you call updateUI() if you remove the call to updateUI()
    everything will work OK.
    merry xmas

  • Problem with JTable and JPanel

    Hi,
    I'm having problems with a JTable in a JPanel. The code is basicly as follows:
    public class mainFrame extends JFrame
            public mainFrame()
                    //A menu is implemeted giving rise to the following actions:
                    public void actionPerformed(ActionEvent evt)
                            String arg = evt.getActionCommand();
                            if(arg.equals("Sit1"))
                            //cells, columnNames are initiated correctly
                            JTable table = new JTable(cells,columnNames);
                            JPanel holdingPanel = new JPanel();
                            holdingPanel.setLayout( new BorderLayout() );
                            JScrollPane scrollPane = new JScrollPane(holdingPanel);
                            holdingPanel.setBackground(Color.white);
                            holdingPanel.add(table,BorderLayout.CENTER);
                            add(scrollPane, "Center");
                            if(arg.equals("Sit2"))
                                    if(scrollPane !=null)
                                            remove(scrollPane);validate();System.out.println("ScrollPane");
                                    if(holdingPanel !=null)
                                            remove(holdingPanel);
                                    if(table !=null)
                                            remove(table);table.setVisible(false);System.out.println("table");
                            //Put other things on the holdingPanel....
            private JScrollPane scrollPane;
            private JPanel holdingPanel;
            private JTable table;
    }The problem is that the table isn't removed. When you choose another situation ( say Sit2), at first the table apparently is gone, but when you press with the mouse in the area it appeared earlier, it appears again. How do I succesfully remove the table from the panel? Removing the panel doesn't seem to be enough. Help is much appreciated...
    Best regards
    Schwartz

    If you reuse the panel and scroll pane throughout the application,
    instantiate them in the constructor, not in an often-called event
    handler. In the event handler, you only do add/remove of the table
    on to the panel. You can't remove the table from the container
    which does not directly contain it.
    if (arg.equals("Sit2")){
      holdingPanel.remove(table);
      holdingPanel.revalidate();
      holdingPanel.repaint(); //sometimes necessary
    }

  • Problem with PropertyChangeListener and JTextField

    I'm having a problem with PropertyChangeListener and JTextField.
    I can not seem to get the propertychange event to fire.
    Anyone have any idea why the code below doesn't work?
    * NewJFrame.java
    * Created on May 15, 2005, 4:21 PM
    import java.beans.*;
    import javax.swing.*;
    * @author wolfgray
    public class NewJFrame extends javax.swing.JFrame
    implements PropertyChangeListener {
    /** Creates new form NewJFrame */
    public NewJFrame() {
    initComponents();
    jTextField1.addPropertyChangeListener( this );
    public void propertyChange(PropertyChangeEvent e) {
    System.out.println(e);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    jTextField1 = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    jFormattedTextField1 = new javax.swing.JFormattedTextField();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setText("jTextField1");
    getContentPane().add(jTextField1, java.awt.BorderLayout.NORTH);
    jFormattedTextField1.setText("jFormattedTextField1");
    jScrollPane1.setViewportView(jFormattedTextField1);
    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    pack();
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new NewJFrame().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
    }

    If you want to listen to changes in the textfield's contents you should use a DocumentListener and not a PropertyChangeListener:
    http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html
    And please use [co[/i]de]  tags when you are posting code (press the code button above the message window).

  • Memory problem with JTextFields

    Hello,
    I have a wierd problem with JTextField and the memory.
    I need to fill a JPanel with different Components (including JTextFields), then do some calculation, remove the Components and filling the JPanel again.
    When i so this too often my i get an OutOfMemory Exception. I narrowed to problem down and wrote a small sample program to demonstrate the problem.
    When i call the method doIT (where the Panel is repeatedly filled) from the main-function everything works fine, but when it is called as a result from the GUI-Button-Event the memory for the JTextFields is not freed (even the call of the Garbage collector changes nothing)
    When i only use JButtons to fill the Panel everything works fine.
    Has anyone an idea why this problem occurs and how i can work around it?
    [Edit] I tested it whith java 1.5.0_06, 1.5.0_11, 1.6.0_02
    Thanks
    Marc
    import java.awt.Frame;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.management.ManagementFactory;
    import java.lang.management.MemoryUsage;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class MemoryTestDLG extends JDialog {
         public MemoryTestDLG(Frame owner) {
              // create Dialog with one Button that calls the testMethod
              super(owner);
              JButton b = new JButton("doIT ...");
              b.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        doIT();
                        setVisible(false);
              getContentPane().add(b);
              pack();
         public void doIT() {
              // Testmethod that fills a JPanel 20 times with Components and clears it
              // again
              JPanel p = new JPanel();
              long memUse1 = 0;
              long memUse2 = 0;
              long memUseTemp = 0;
              for (int count = 0; count < 20; count++) {
                   // Clear the panel
                   p.removeAll();
                   // Get memory usage before the task
                   Runtime.getRuntime().gc();
                   memUse1 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
                             .getUsed();
                   // Fill Panel with components
                   for (int i = 0; i < 200; i++) {
                        // The Buttons seem to be released without any problem
                        p.add(new JButton("test" + Math.random()));
                        // JTextFields are not released when used from the dialog.
                        p.add(new JTextField("test " + Math.random()));
                   // get memory usage after the task
                   Runtime.getRuntime().gc();
                   memUseTemp = memUse2;
                   memUse2 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
                             .getUsed();
                   // print Memory results
                   System.out.println("Memory Usage: " + f(memUse1) + "   ->"
                             + f(memUse2) + " [ Used:" + f(memUse2 - memUse1)
                             + " ] [ Freed: " + f(memUseTemp - memUse1) + "]");
         public String f(long m) // formats the output
              String s = "" + m;
              while (s.length() < 8)
                   s = " " + s;
              return s;
         public static void main(String[] args) {
              MemoryTestDLG d = new MemoryTestDLG(null);
              System.out
                        .println("------------------ Direct Call (all is OK) -------------------");
              d.doIT(); // Memory is freed with every call to JPanel.removeAll()
              System.out
                        .println("------------ Call from Dialog (memory is not freed) -------------");
              // The Memory keeps blocked
              d.setModal(true);
              d.setVisible(true);
              System.exit(0);
    }Message was edited by:
    marcvomorc

    Thank you for your answer,
    In this sample the programm does not run out of memory. But when you look at the output you see, that in the first run (direct call) the memory ist freed immediately when tha panel is cleared but in the second run (from the Button) the memory usage is getting bigger and bigger. Wenn you change the number of components to 2000 (4000)
    // Fill Panel with components
            for (int i = 0; i < 2000; i++) {
                // The Buttons seem to be released without any problem
    //... ...and use the default memory settings (69mb heap) the programm runns out of memory.
    I get the following output:
    ------------------ Direct Call (all is OK) -------------------
    Memory Usage:   445504   -> 8121016 [ Used: 7675512 ] [ Freed:  -445504]
    Memory Usage:   617352   -> 8114336 [ Used: 7496984 ] [ Freed:  7503664]
    Memory Usage:   810488   -> 8491768 [ Used: 7681280 ] [ Freed:  7303848]
    Memory Usage:   943704   -> 8114976 [ Used: 7171272 ] [ Freed:  7548064]
    Memory Usage:   836760   -> 8505072 [ Used: 7668312 ] [ Freed:  7278216]
    Memory Usage:   978352   -> 8114784 [ Used: 7136432 ] [ Freed:  7526720]
    Memory Usage:   835552   -> 8498288 [ Used: 7662736 ] [ Freed:  7279232]
    Memory Usage:   977096   -> 8114312 [ Used: 7137216 ] [ Freed:  7521192]
    Memory Usage:   835640   -> 8498376 [ Used: 7662736 ] [ Freed:  7278672]
    Memory Usage:   977296   -> 8115000 [ Used: 7137704 ] [ Freed:  7521080]
    Memory Usage:   835392   -> 8504872 [ Used: 7669480 ] [ Freed:  7279608]
    Memory Usage:   976968   -> 8115192 [ Used: 7138224 ] [ Freed:  7527904]
    Memory Usage:   836224   -> 8501624 [ Used: 7665400 ] [ Freed:  7278968]
    Memory Usage:   977840   -> 8115120 [ Used: 7137280 ] [ Freed:  7523784]
    Memory Usage:   835664   -> 8498256 [ Used: 7662592 ] [ Freed:  7279456]
    Memory Usage:   976856   -> 8114384 [ Used: 7137528 ] [ Freed:  7521400]
    Memory Usage:   835784   -> 8502848 [ Used: 7667064 ] [ Freed:  7278600]
    Memory Usage:   977360   -> 8114592 [ Used: 7137232 ] [ Freed:  7525488]
    Memory Usage:   835496   -> 8502720 [ Used: 7667224 ] [ Freed:  7279096]
    Memory Usage:   976440   -> 8115128 [ Used: 7138688 ] [ Freed:  7526280]
    ------------ Call from Dialog (memory is not freed) -------------
    Memory Usage:   866504   -> 8784320 [ Used: 7917816 ] [ Freed:  -866504]
    Memory Usage:  7480760   ->14631152 [ Used: 7150392 ] [ Freed:  1303560]
    Memory Usage: 14245264   ->22127104 [ Used: 7881840 ] [ Freed:   385888]
    Memory Usage: 19302896   ->27190744 [ Used: 7887848 ] [ Freed:  2824208]
    Memory Usage: 27190744   ->35073944 [ Used: 7883200 ] [ Freed:        0]
    Memory Usage: 31856624   ->39740176 [ Used: 7883552 ] [ Freed:  3217320]
    Memory Usage: 39740176   ->47623040 [ Used: 7882864 ] [ Freed:        0]
    Memory Usage: 44410480   ->52293864 [ Used: 7883384 ] [ Freed:  3212560]
    Memory Usage: 52293864   ->58569304 [ Used: 6275440 ] [ Freed:        0]
    Memory Usage: 58569304   ->64846400 [ Used: 6277096 ] [ Freed:        0]
    Exception occurred during event dispatching:
    java.lang.OutOfMemoryError: Java heap spacewhen I outcomment the adding of the JButtons the amount of freed memory is 0 in the second run. So my guess is, that there is a problem with freeing the memory for the JTextFields.
    Memory Usage:   447832   -> 6509960 [ Used: 6062128 ] [ Freed:  6332768]
    Memory Usage:   722776   -> 6785632 [ Used: 6062856 ] [ Freed:  5787184]
    ------------ Call from Dialog (memory is not freed) -------------
    Memory Usage:   468880   -> 6770240 [ Used: 6301360 ] [ Freed:  -468880]
    Memory Usage:  6770240   ->13016264 [ Used: 6246024 ] [ Freed:        0]
    Memory Usage: 13016264   ->19297080 [ Used: 6280816 ] [ Freed:        0]
    Memory Usage: 19297080   ->25570152 [ Used: 6273072 ] [ Freed:        0]
    Memory Usage: 25570152   ->31849160 [ Used: 6279008 ] [ Freed:        0]
    Memory Usage: 31849160   ->38124368 [ Used: 6275208 ] [ Freed:        0]
    Memory Usage: 38124368   ->44402072 [ Used: 6277704 ] [ Freed:        0]
    Memory Usage: 44402072   ->50677928 [ Used: 6275856 ] [ Freed:        0]
    Memory Usage: 50677928   ->56955880 [ Used: 6277952 ] [ Freed:        0]
    Memory Usage: 56955880   ->63232152 [ Used: 6276272 ] [ Freed:        0]
    Exception occurred during event dispatching:
    java.lang.OutOfMemoryError: Java heap spaceAdditionally the JPanel I am using is not displayed on the screen. It stays invisible the whole time, but i cannot work around that, because the calculation is depending on the values being in components on the JPanel)
    Marc

Maybe you are looking for

  • Problem with GuardianEdge and Discoverer export

    We're having problems doing XLS or SLK exports out of Discoverer Plus 10g and appears to only be happening on PCs where the GuardianEdge encryption product has been installed. In fact, we can export to a shared drive (i.e. server not protected by Gua

  • Can't send email over home wi-fi network

    Everything about ihone has been great except for baffling email problem. Prior to this I've never had a problem setting up POP email on various Macs, PDAs, cellphones... I'm in the UK so on the o2 network. I have correctly filled in all the correct r

  • Wait step not copmleting

    Hi Experts, I am working on simple BPM scenario with recieve,send and wait steps.I have placed wait step between recieve and send step. The issue is wait step is not completing in process.In wait step i have given 2minutes duration. Anybody plz help

  • Putting a ringtone in iTunes on the iPhone

    I have 3rd party software that converts mp3 files into ringtones.  It automatically makes the file an .m4r file, and puts it into the iTunes tones library.  I connected my iPhone 4 (running iOS 6) to my iMac, but iTunes will not let me drag the tone

  • WHEN-TREE-NODE-SELECTED

    Hello alllll i have a master-detail block besides a tree block All i wanna do Simply and logically is to select a tree node then a Master-Detail records related to this tree node is to be retrieved... _i have the following code in the WHEN-TREE-NODE-