Java Swing GUI Problem

(components get distorted)

Page 1 of 1

5 Replies - 3105 Views - Last Post: 05 October 2010 - 02:36 PM Rate Topic: -----

#1 jub_csstud  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 18-February 10

Java Swing GUI Problem

Posted 03 October 2010 - 08:42 AM

Hi there! I am working on a school project on assembler simulation. I am having a problem with my swing GUI. It's not yet done as I will still put other features in it but it can already be run. There would be times that after I run it or if I just leave it running on the background for some time, all the components of the GUI would be "distorted". It becomes "distorted" in a way that panels partly hide other components, text areas get smaller, etc. I used gridbaglayout as layout manager. I code my GUI's this way and I have no problems until now. I probably missed out on something but I just couldn't figure it out. I added a picture attachment to help convey what I mean. :)
By the way here's the code:

package MP2;

/**
 *
 * GUI
 */

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class GUI extends JPanel implements ActionListener
{
   /* Global Variables */
   JMenuBar fileBar = new JMenuBar(),
            helpBar = new JMenuBar();

   JMenu fileMenu = new JMenu("File"),
            helpMenu = new JMenu("Help");

   JMenuItem helpItem = new JMenuItem("Help"),
            aboutItem = new JMenuItem("About"),
            creditsItem = new JMenuItem("Credits"),
            exitItem = new JMenuItem("Quit"),
            fromFileItem = new JMenuItem("Choose from File"),
            saveFileItem = new JMenuItem("Save File"),
            compileFileItem = new JMenuItem("Compile File"),
            runFileItem = new JMenuItem("Run File");

   JFileChooser fileChooser = new JFileChooser();

   JTextArea inputArea = new JTextArea(10, 20),
            msgArea = new JTextArea(10, 10),
            memArea = new JTextArea(10, 10);

   JScrollPane inputScroll = new JScrollPane(inputArea);

   String message = "";
   
   private JPanel returnPanel ()
   {
      JSeparator mainSeparator = new JSeparator(JSeparator.HORIZONTAL),
            bottomSeparator = new JSeparator(JSeparator.VERTICAL);

      JLabel memLabel = new JLabel("Memory View"),
            msgLabel = new JLabel("Message");

      JPanel memPanel = new JPanel(),
            msgPanel = new JPanel(),
            bottomPanel = new JPanel(),
            memMsgPanel = new JPanel(),
            mainPanel = new JPanel(),
            inputPanel = new JPanel(),
            menuPanel = gradPanel(),
            memHeadPanel = gradPanel(),
            msgHeadPanel = gradPanel();

      Font menuFont = new Font("sansserif", Font.BOLD, 12);

      fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
      fileChooser.setFileFilter(new FileFilter()                   // override setfilefilter to select text files only
                  {
	             public boolean accept(File f) // accepts only files with extension txt
                     {
		        return f.getName().toLowerCase().endsWith(".txt");
	             }

	             public String getDescription()
                     {
		        return "(*.txt)";
	             }
                  });

      /* Add other attributes to menu bars and menus */
      helpMenu.setFont(menuFont);                      // set font
      helpMenu.setForeground(new Color(49, 79, 79));   // sets text color

      helpBar.setOpaque(false);                        // sets menu bar transparent; foreground visible
      helpBar.setBorderPainted(false);                 // sets menu bar border unpainted; "seamless" menu bar

      fileMenu.setFont(menuFont);                      // set font
      fileMenu.setForeground(new Color(49, 79, 79));   // sets text color

      fileBar.setOpaque(false);                        // sets menu bar transparent; foreground visible
      fileBar.setBorderPainted(false);

      /* Add menus to menu bars and add menu items to menus */
      fileMenu.add(fromFileItem);
      fileMenu.add(saveFileItem);
      fileMenu.add(compileFileItem);
      fileMenu.add(runFileItem);
      fileMenu.add(exitItem);

      helpMenu.add(helpItem);
      helpMenu.add(creditsItem);
      helpMenu.add(aboutItem);

      fileBar.add(fileMenu);
      helpBar.add(helpMenu);

      /* Set key controls to menu items */
      fileMenu.setMnemonic('F');
      helpMenu.setMnemonic('H');
      fromFileItem.setMnemonic('C');
      fromFileItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
      saveFileItem.setMnemonic('S');
      saveFileItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
      compileFileItem.setMnemonic('C');
      compileFileItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.ALT_MASK));
      runFileItem.setMnemonic('C');
      runFileItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.ALT_MASK));
      exitItem.setMnemonic('Q');
      exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.ALT_MASK));

      /* Add actionListener to menu items */
      fromFileItem.addActionListener(this);
      saveFileItem.addActionListener(this);
      compileFileItem.addActionListener(this);
      runFileItem.addActionListener(this);
      exitItem.addActionListener(this);

      /* Set text area properties */
      inputArea.setEditable(true);
      msgArea.setEditable(false);
      memArea.setEditable(false);

      /* Add components and properties to panels */
      menuPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
      menuPanel.add(fileBar);
      menuPanel.add(helpBar);

      memHeadPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
      memHeadPanel.add(memLabel);

      msgHeadPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
      msgHeadPanel.add(msgLabel);

      memPanel.setLayout(new BorderLayout());
      memPanel.add(memHeadPanel, BorderLayout.NORTH);
      memPanel.add(memArea,BorderLayout.CENTER);

      msgPanel.setLayout(new BorderLayout());
      msgPanel.add(msgHeadPanel, BorderLayout.NORTH);
      msgPanel.add(msgArea, BorderLayout.CENTER);

      /* Add components to return panel */
      GridBagLayout gBag = new GridBagLayout();
      GridBagConstraints cons = new GridBagConstraints();

      this.setLayout(gBag);

      // Menu bar
      this.buildConstraints(cons, 0, 0, 5, 1, 0, 15);
      cons.fill = GridBagConstraints.HORIZONTAL;
      cons.anchor = GridBagConstraints.CENTER;
      gBag.setConstraints(menuPanel, cons);
      this.add(menuPanel);

      // Separator
      this.buildConstraints(cons, 0, 1, 5, 1, 0, 10);
      cons.fill = GridBagConstraints.HORIZONTAL;
      cons.anchor = GridBagConstraints.CENTER;
      gBag.setConstraints(mainSeparator, cons);
      this.add(mainSeparator);

      // Input Panel
      this.buildConstraints(cons, 0, 2, 5, 1, 0, 40);
      cons.fill = GridBagConstraints.NONE;
      cons.anchor = GridBagConstraints.CENTER;
      gBag.setConstraints(inputScroll, cons);
      this.add(inputScroll);

      // Separator
      this.buildConstraints(cons, 0, 3, 5, 1, 0, 10);
      cons.fill = GridBagConstraints.HORIZONTAL;
      cons.anchor = GridBagConstraints.CENTER;
      gBag.setConstraints(mainSeparator, cons);
      this.add(mainSeparator);

      // Memory Panel
      this.buildConstraints(cons, 0, 4, 2, 1, 48, 25);
      cons.fill = GridBagConstraints.NONE;
      cons.anchor = GridBagConstraints.CENTER;
      gBag.setConstraints(memPanel, cons);
      this.add(memPanel);

      // Separator
      this.buildConstraints(cons, 2, 4, 1, 1, 4, 0);
      cons.fill = GridBagConstraints.VERTICAL;
      cons.anchor = GridBagConstraints.CENTER;
      gBag.setConstraints(bottomSeparator, cons);
      this.add(bottomSeparator);

      // Message Panel
      this.buildConstraints(cons, 3, 4, 2, 1, 48, 0);
      cons.fill = GridBagConstraints.NONE;
      cons.anchor = GridBagConstraints.CENTER;
      gBag.setConstraints(msgPanel, cons);
      this.add(msgPanel);
      
      return this;
      
   } // end returnPanel

   /* Gradient Panel */
   private JPanel gradPanel()
   {
      JPanel panel =  new JPanel()
      {
         @Override
         protected void paintComponent(Graphics g)      // override paintComponent
         {
            if (!isOpaque())                            // if panel is not opaque
            {
               super.paintComponent(g);                 // add new method (or in this case copy constructor) to original paintComponent
               return;
            }

            Graphics2D g2d = (Graphics2D)g;             // cast g with graphics2D

            int w = getWidth();                         // width of panel
            int h = getHeight();                        // height of panel

            Color color2 = new Color(112, 138, 144);    // second color

            // Paint a gradient from top to bottom
            GradientPaint gp = new GradientPaint(0, 0, Color.WHITE, 0, h, color2);

            g2d.setPaint(gp);
            g2d.fillRect(0, 0, w, h);

            setOpaque(false);            // prevents UI delegate from painting panel with a constant color
            super.paintComponent(g);     // paint gradient
            setOpaque(true);
         } // end overriding paintComponent
      };

      return panel;
   } //  end gradPanel

   /* Builds constraints of grid bag layout */
   private void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy)
   {
      gbc.gridx = gx;
      gbc.gridy = gy;
      gbc.gridwidth = gw;
      gbc.gridheight = gh;
      gbc.weightx = wx;
      gbc.weighty = wy;
   }  // end buildConstraints

   private static void getFrame ()
   {
      GUI gui = new GUI();
      JFrame frame = new JFrame("Assembler Simulation");
      JFrame.setDefaultLookAndFeelDecorated(true);
      frame.setLocation(430, 150);
      frame.setResizable(false);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(gui.returnPanel());    // call returnPanel to add components to this frame
      frame.pack();
      frame.setVisible(true);
   } // end getFrame

   /* Handles flow of code */
   public static void main (String args[])
   {
      getFrame();
   } // end main

    public void actionPerformed(ActionEvent click)
    {
       if (click.getSource() == fromFileItem)
       {
          int returnFile = fileChooser.showOpenDialog(GUI.this);

          if (returnFile == JFileChooser.APPROVE_OPTION)     // if user chooses to open the file
          {
             inputArea.setText("");

             try
             {
	        File f = fileChooser.getSelectedFile();       // selected file
       	        printFileToTextArea(f);                       // call function to process file
       	     }
             catch(Exception e)
             {
    	        message = "Error reading file: " + e;
                getMessage(message, "Load File Error", JOptionPane.ERROR_MESSAGE);
       	     }
          }
          else                                                // if user chose to cancel opening of file
          {
             message = "Open command cancelled by user";
             getMessage(message, "File Load Cancelled", JOptionPane.INFORMATION_MESSAGE);
          }
          inputArea.setCaretPosition(inputArea.getDocument().getLength());
       }
       else if (click.getSource() == saveFileItem)
       {
          int saveFile = fileChooser.showSaveDialog(GUI.this);

          if (saveFile == JFileChooser.APPROVE_OPTION)
          {
             File file = new File( fileChooser.getSelectedFile( ) + ".txt" ); // ala p ni replace if exist

             try
             {
                saveTextFile(file);
             }
             catch (IOException e)
             {
                message = "Error: " + e + " Cannot save file";
                getMessage(message, "Save File Error", JOptionPane.ERROR_MESSAGE);
             }
          }
       }
       else if (click.getSource() == compileFileItem)
       {

       }
       else if (click.getSource() == runFileItem)
       {
          ExecuteFile exec = new ExecuteFile();
          exec.execute(inputArea.getText());
       }
       else if (click.getSource() == exitItem)
       {
          int out = JOptionPane.showConfirmDialog(this, "Are you sure you want to exit?", "Exit", JOptionPane.YES_NO_OPTION);

          if (out == JOptionPane.YES_OPTION)
             System.exit(0);
       }

    } // end actionPerformed

    /* Saves text from input area to text file */
    private void saveTextFile (File text) throws IOException
    {
       PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(text)),true);

       StringTokenizer tokenize = new StringTokenizer(inputArea.getText(), "\n");

       while (tokenize.hasMoreTokens())
       {
          out.println(tokenize.nextToken());
       }

       out.close();
       
    } // end saveTextFile

    /* Prints text file into input area */
    private void printFileToTextArea(File f)
    {
       String strLine;
      
       try
       {
          FileInputStream inp = new FileInputStream(f);
	  BufferedReader br = new BufferedReader(new InputStreamReader(inp));

          while ((strLine = br.readLine()) != null)
          {
	     inputArea.append(strLine + "\n");
	  }
       }
       catch(Exception e) // catch exception if file cannot be read
       {
          message = "Error reading file" + e;
          getMessage(message, "Error reading file", JOptionPane.ERROR_MESSAGE);
       }
   } // end printFile

    /* Handles messages of JOptionPanes */
    private void getMessage(Object m, String title, int msgType)
    {
      JFrame frame = new JFrame();

      JOptionPane.showMessageDialog(frame, m, title, msgType);
   } // end getMessage
   
} // end of class




I hope you can help me..
Thank you so much if you will take the time to read my post and help me.. :)

Is This A Good Question/Topic? 0
  • +

Replies To: Java Swing GUI Problem

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,051
  • Joined: 15-July 08

Re: Java Swing GUI Problem

Posted 03 October 2010 - 11:29 AM

Where's this picture attachment?

I'm running it just fine and it looks good! I like the way that you've done the menus!
Was This Post Helpful? 0
  • +
  • -

#3 jub_csstud  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 18-February 10

Re: Java Swing GUI Problem

Posted 04 October 2010 - 05:53 AM

View PostDogstopper, on 03 October 2010 - 10:29 AM, said:

Where's this picture attachment?


oops.. I forgot to attach the picture.. :) the picture is attached along with this reply.

Quote

I'm running it just fine and it looks good! I like the way that you've done the menus!


Thank you vary much! :) It's not yet done though. I'm still going to adjust the components so that they will not look cramped. Did it really work fine? Hmm.. I wonder if it's on the system I'm running. I have worked on several school projects this semester and the gui's haven't been doing anything strange really until now..

Hmm.. It's really strange..

Attached Image
Was This Post Helpful? 0
  • +
  • -

#4 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,051
  • Joined: 15-July 08

Re: Java Swing GUI Problem

Posted 04 October 2010 - 08:21 AM

What did you do to cause the weird look. I was just minimizing it and such. Tell me what you did and I'll try to reproduce it.
Was This Post Helpful? 0
  • +
  • -

#5 jub_csstud  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 18-February 10

Re: Java Swing GUI Problem

Posted 05 October 2010 - 07:49 AM

Actually, I don't know where I did wrong.. I've decided not to use the gridbag layout anymore. And I just layered border layout and others. I have not been experiencing any problem now.. I don't know.. Hehe.. But thanks for offering help.. Really appreciate it.. :)
Was This Post Helpful? 0
  • +
  • -

#6 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,051
  • Joined: 15-July 08

Re: Java Swing GUI Problem

Posted 05 October 2010 - 02:36 PM

Glad you figured it out :)
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1