Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Beginning Swing help - resize API

  1. #1
    Junior Member
    Join Date
    Dec 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Beginning Swing help - resize API

    Hi,

    I'm working on a project where I am creating an Swing only API with buttons to draw graphs. Below is my code, when I run it and resize the window, the API goes blank. Is there anything simple I can do to make this more user friendly?

    Thanks!

    public GUI()
    {
    super("Bar Graphs"); // Window title

    // Get the container and add the buttons

    Container c = getContentPane();

    c.setLayout(new FlowLayout());

    quizButton = new JButton("Quiz Averages"); // Create a button
    quizButton.addActionListener( this ); // Register the event handler
    c.add(quizButton); // Add the button to the Application

    homeworkButton = new JButton("Homework Averages"); // Create a button
    homeworkButton.addActionListener( this ); // Register the event handler
    c.add(homeworkButton); // Add the button to the Application

    .....4 more buttons added

    public void paint( Graphics g )
    {

    super.paint(g);

    g.setColor(Color.red);
    g.setFont(new Font("Times", Font.BOLD, 22));

    if (drawQuizGraph == true)//Quiz button clicked, draw the graph when repaint() called
    {
    //graph label
    g.drawString("Quiz Averages", 10, 150);

    //Y axis graph labels
    g.drawString("0 Students", 10, 750);
    g.drawString("10 Students", 10, 650);
    g.drawString("20 Students", 10, 550);
    g.drawString("30 Students", 10, 450);
    g.drawString("40 Students", 10, 350);
    g.drawString("50+ Students", 10, 250);

    //X axis graph labels
    g.drawString("100-95", 145, 780);
    g.drawString("94-90", 245, 780);
    g.drawString("89-85", 345, 780);
    g.drawString("84-80", 445, 780);
    g.drawString("79-75", 545, 780);
    ....more bars drawn

    // Event Handler Code
    public void actionPerformed( ActionEvent e )
    {
    if (e.getSource() == quizButton)
    {
    drawQuizGraph = true;
    repaint();
    }
    g.drawString("74 or less", 645, 780);

    //draw the bars
    g.setColor(Color.blue);
    int x1 = 165;
    int y1 = 700;
    g.fillRect(x1, y1, 50, 50);

    g.setColor(Color.green);
    x1 = 265;
    y1 = 700;
    g.fillRect(x1, y1-100, 50, 150);
    ...more bars


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Beginning Swing help - resize API

    You need to edit your post above and place [code] [/code] tags around your posted code so that it retains its formatting and is easier to read.

    That being said, I'm confused in that it appears that you are dealing directly with a Graphics object, g, in your actionPerformed method, and that suggests that your code design is bad. Please tell and show us more. Are you in fact working with a Graphics object? If so where are you getting it from? Also, you almost never want to draw in a paint(...) method but rather a JPanel's paintComponent method for several reasons.

  3. #3
    Junior Member
    Join Date
    Dec 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Beginning Swing help - resize API

    Quote Originally Posted by curmudgeon View Post
    You need to edit your post above and place [code] [/code] tags around your posted code so that it retains its formatting and is easier to read.

    That being said, I'm confused in that it appears that you are dealing directly with a Graphics object, g, in your actionPerformed method, and that suggests that your code design is bad. Please tell and show us more. Are you in fact working with a Graphics object? If so where are you getting it from? Also, you almost never want to draw in a paint(...) method but rather a JPanel's paintComponent method for several reasons.
    I'm sure it's loaded with poor design as I am new to java and swing has been tough for me to grasp. I basically have a data file with scores I am reading into to a custom object. Based on these scores I want to create an API which will display diff avgs in a bar graph based on the button clicked. I have everything down except the API which I am having trouble laying out into a clean format display.

    This is my first post in this forum and I appreciate your advice.

    I can post my code when I get back to my pc

  4. #4
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Beginning Swing help - resize API

    OK, we'll wait for you to return to your PC.

  5. #5
    Junior Member
    Join Date
    Dec 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Beginning Swing help - resize API

    Quote Originally Posted by curmudgeon View Post
    OK, we'll wait for you to return to your PC.

    The code for my GUI class is below. I havent implemented the size of the graph bars as they are currently hardcoded.

    My questions/problems so far are:

    When I draw a graph and resize the window, the GUI goes blank, I would like it to resize with the window if within my extremely beginner scope...
    Any suggestions on how to clean up the display/creation of the GUI? I only want to use Swing and keep it simple/primitive.

    THanks!


     
     
     
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Iterator;
     
    @SuppressWarnings("serial")
     
    public class GUI extends JFrame
    	implements ActionListener
    {
    		//API buttons
    		private JButton quizButton;
    		private JButton homeworkButton;
    		private JButton midtermButton;
    		private JButton finalprojectButton;
    		private JButton coursescoreButton;
    		private JButton coursegradeButton;
     
    		//button flags
    		private boolean drawQuizGraph = false;
    		private boolean drawHomeworkGraph = false;
    		private boolean drawMidtermGraph = false;
    		private boolean drawFinalProjectGraph = false;
    		private boolean drawCourseAveragesGraph = false;
    		private boolean drawCourseGradesGraph = false;
     
    		//grade and score counters
    		private int aGrades = 0;
    		private int aMinusGrades = 0;
    		private int bPlusGrades = 0;
    		private int bGrades = 0;
    		private int bMinusGrades = 0;
    		private int cGrades = 0;
    		private int midtermScore = 0;
    		private int finalProjectScore = 0;
     
    		// Constructor
    		public GUI(HashMap<String, Student> studentMap) 
    		{
    			super("Graphs");  // Window title
     
    			// Get the container and add the buttons
     
    				Container c = getContentPane();
     
    				c.setLayout(new FlowLayout());
     
    				quizButton = new JButton("Quiz Averages");	// Create a button
    				quizButton.addActionListener( this );	// Register the event handler
    				c.add(quizButton);			// Add the button to the Application
     
    				homeworkButton = new JButton("Homework Averages");	// Create a button
    				homeworkButton.addActionListener( this );	// Register the event handler
    				c.add(homeworkButton);			// Add the button to the Application
     
    				midtermButton = new JButton("Midterm Scores");	// Create a button
    				midtermButton.addActionListener( this );	// Register the event handler
    				c.add(midtermButton);			// Add the button to the Application
     
    				finalprojectButton = new JButton("Final Project Scores");	// Create a button
    				finalprojectButton.addActionListener( this );	// Register the event handler
    				c.add(finalprojectButton);			// Add the button to the Application
     
    				coursescoreButton = new JButton("Course Averages");	// Create a button
    				coursescoreButton.addActionListener( this );	// Register the event handler
    				c.add(coursescoreButton);			// Add the button to the Application
     
    				coursegradeButton = new JButton("Course Grades");	// Create a button
    				coursegradeButton.addActionListener( this );	// Register the event handler
    				c.add(coursegradeButton);			// Add the button to the Application
     
     
    				Collection<Student> students = studentMap.values();
    				Iterator<Student> mapItr = students.iterator();//map iterator
    				while (mapItr.hasNext())//iterate to end of map
    				{
    					Student currentStudent = mapItr.next();
    					if (currentStudent.getCourseGrade() == "A")
    						aGrades++;
    					else if (currentStudent.getCourseGrade() == "B+")
    						bPlusGrades++;
    					else if (currentStudent.getCourseGrade() == "B")
    						bGrades++;
    					else if (currentStudent.getCourseGrade() == "B-")
    						bMinusGrades++;
    					else 
    						cGrades++;
     
    					System.out.println("Totals printing");
    					System.out.println(aGrades);
    					System.out.println(bGrades);
    					System.out.println(cGrades);
     
     
    				}
     
    		}
     
    		public void paintGraphYLabels( Graphics g )//draws Y axis graph labels
    		{
     
    			g.drawString("0 Students", 10, 750);
    			g.drawString("10 Students", 10, 650);
    			g.drawString("20 Students", 10, 550);
    			g.drawString("30 Students", 10, 450);
    			g.drawString("40 Students", 10, 350);
    			g.drawString("50+ Students", 10, 250);
    		}
    		public void paintGraphXLabels( Graphics g )//draws X axis graph labels
    		{
     
    			g.drawString("100-95", 145, 780);
    			g.drawString("94-90", 245, 780);
    			g.drawString("89-85", 345, 780);
    			g.drawString("84-80", 445, 780);
    			g.drawString("79-75", 545, 780);
    			g.drawString("74 or less", 645, 780);
    		}
     
    		public void paintGraphBars( Graphics g )//method draws actual graph bars
    		{
    			//draw the bars
    			g.setColor(Color.blue);
    			int x1 = 165; 
    			int y1 = 700;
    			g.fillRect(x1, y1, 50, 50);
     
    			g.setColor(Color.green);
    			x1 = 265; 
    			y1 = 700;
    			g.fillRect(x1, y1-100, 50, 150);
     
    			g.setColor(Color.orange);
    			x1 = 365; 
    			y1 = 700;
    			g.fillRect(x1, y1-100, 50, 150);
     
    			g.setColor(Color.yellow);
    			x1 = 465; 
    			y1 = 700;
    			g.fillRect(x1, y1-100, 50, 150);
     
    			g.setColor(Color.red);
    			x1 = 565; 
    			y1 = 700;
    			g.fillRect(x1, y1-100, 50, 150);
     
    			g.setColor(Color.pink);
    			x1 = 665; 
    			y1 = 700;
    			g.fillRect(x1, y1-150, 50, 200);
     
    		}
    		public void paint( Graphics g ) 
    		{
     
    			super.paint(g);		
     
    			g.setColor(Color.black);
    			g.setFont(new Font("Times", Font.BOLD, 20));
     
    			if (drawQuizGraph == true)//Quiz button clicked, draw the graph
    			{
     
    				g.drawString(" Quiz Averages", 10, 150);//graph title
    				paintGraphXLabels(g);
    				paintGraphYLabels(g);
    				paintGraphBars(g);
     
    				//set flag to false
    				drawQuizGraph = false;
     
     
    			}
    			else if (drawHomeworkGraph == true)//Course Grade button clicked, draw the graph
    			{
     
    				g.drawString(" Homework Averages", 10, 150);//graph title
    				paintGraphXLabels(g);
    				paintGraphYLabels(g);
    				paintGraphBars(g);
     
    				drawHomeworkGraph = false;
     
    			}
    			else if (drawMidtermGraph == true)//Course Grade button clicked, draw the graph
    			{
    				g.drawString(" Midterm Scores", 10, 150);//graph title
    				paintGraphXLabels(g);
    				paintGraphYLabels(g);
    				paintGraphBars(g);
     
    				drawMidtermGraph = false;
     
    			}
    			else if (drawFinalProjectGraph == true)//Course Grade button clicked, draw the graph
    			{
    				g.drawString(" Final Project Scores", 10, 150);//graph title
    				paintGraphXLabels(g);
    				paintGraphYLabels(g);
    				paintGraphBars(g);
     
    				drawFinalProjectGraph = false;	
    			}
    			else if (drawCourseAveragesGraph == true)//Course Grade button clicked, draw the graph
    			{
    				g.drawString(" Course Score Averages", 10, 150);//graph title
    				paintGraphXLabels(g);
    				paintGraphYLabels(g);
    				paintGraphBars(g);
     
    				drawCourseAveragesGraph = false;	
    			}
    			else if (drawCourseGradesGraph == true)//Course Grade button clicked, draw the graph
    			{
    				g.drawString(" Course Grade Averages", 10, 150);//graph title
    				paintGraphYLabels(g);
     
    				//X axis labels
    				g.drawString("A", 185, 780);
    				g.drawString("A-", 285, 780);
    				g.drawString("B+", 385, 780);
    				g.drawString("B", 485, 780);
    				g.drawString("B-", 585, 780);
    				g.drawString("C", 685, 780);
     
     
    				g.setColor(Color.blue);
    				int x1 = 175; 
    				int y1 = 700;
    				g.fillRect(x1, y1, 50, 50);
     
    				g.setColor(Color.green);
    				x1 = 275; 
    				y1 = 700;
    				g.fillRect(x1, y1-100, 50, 150);
     
     
    				g.setColor(Color.orange);
    				x1 = 375; 
    				y1 = 700;
    				g.fillRect(x1, y1-100, 50, 150);
     
    				g.setColor(Color.yellow);
    				x1 = 475; 
    				y1 = 700;
    				g.fillRect(x1, y1-100, 50, 150);
     
    				g.setColor(Color.red);
    				x1 = 575; 
    				y1 = 700;
    				g.fillRect(x1, y1-100, 50, 150);
     
    				g.setColor(Color.pink);
    				x1 = 675; 
    				y1 = 700;
    				g.fillRect(x1, y1-150, 50, 200);
     
    				drawCourseGradesGraph = false;
    			}
    		}
     
     
    		// Event Handler Code, for each button clicked, set flag to true and corresponding draw graph
    		public void actionPerformed( ActionEvent e ) 
    		{
    			if (e.getSource() == quizButton) 
    			{
    				drawQuizGraph = true;
    				repaint();
    			}
    			else if (e.getSource() == homeworkButton) 
    			{
    				drawHomeworkGraph = true;
    				repaint();	
    			}
    			else if (e.getSource() == midtermButton) 
    			{
    				drawMidtermGraph = true;
    				repaint();
    			}
    			else if (e.getSource() == finalprojectButton) 
    			{
    				drawFinalProjectGraph = true;
    				repaint();
    			}
    			else if (e.getSource() == coursescoreButton) 
    			{
    				drawCourseAveragesGraph = true;
    				repaint();
    			}
    			else if (e.getSource() == coursegradeButton) 
    			{
    				drawCourseGradesGraph = true;
    				repaint();
    			}
     
    		}
     
    	}

  6. #6
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Beginning Swing help - resize API

    You're problem is that you've got program logic inside of your painting method, code that changes the state of your program which is something that you should never do. Realize that this logic gets called at unpredictable times, including multiple times when you re-size your application. Instead put that logic elsewhere and use your painting methods for painting only, not to change boolean variables.

    Another big error is that you're drawing in the paint(...) method of a JFrame, something else that should almost never be done. Instead read the painting with swing and AWt tutorial and draw with a paintComponent method that is held inside of a JPanel or JComponent extending class.

    --- Update ---

    What you're doing is essentially this:

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
     
    @SuppressWarnings("serial")
    public class GUI2 extends JFrame implements ActionListener {
       private static final int PREF_W = 400;
       private static final int PREF_H = 300;
       private JButton quizButton  = new JButton("Quiz Averages");
       private boolean drawQuizGraph = false;
       public GUI2() {
          super("Graphs");
     
          JPanel panel = new JPanel();
          quizButton.addActionListener(this);
          panel.add(quizButton);
          add(panel, BorderLayout.NORTH);
     
          setPreferredSize(new Dimension(PREF_W, PREF_H));
       }
     
       public void paint(Graphics g) {
     
          super.paint(g);
     
          g.setColor(Color.black);
          g.setFont(new Font("Times", Font.BOLD, 20));
     
          if (drawQuizGraph) // == true is redundant and unnecessary 
          {
     
             g.drawString(" Quiz Averages", 10, 150);
     
             drawQuizGraph = false;
     
          }
       }
     
       public void actionPerformed(ActionEvent e) {
          if (e.getSource() == quizButton) {
             drawQuizGraph = true;
             repaint();
          }
     
       }
     
       public static void main(String[] args) {
          GUI2 gui = new GUI2();
     
          gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          gui.pack();
          gui.setLocationRelativeTo(null);
          gui.setVisible(true);
       }
     
    }


    --- Update ---

    Note that even if you comment out the offending line:

    // drawQuizGraph = false;

    the code now works but when you resize there is nasty flashing of the graphics. This is solved by using the automatic double buffering provided by Swing derived JComponent classes (such as JPanel) paintComponent method. Test this example:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    @SuppressWarnings("serial")
    public class GUI3 extends JPanel {
       private static final int PREF_W = 400;
       private static final int PREF_H = 300;
       private JButton quizButton = new JButton(new QuizButtonAction("Quiz Averages"));
       private boolean drawQuizGraph = false;
     
       public GUI3() {
          JPanel panel = new JPanel();
     
          panel.add(quizButton);
          add(panel, BorderLayout.NORTH);
       }
     
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.setColor(Color.black);
          g.setFont(new Font("Times", Font.BOLD, 20));
          Graphics2D g2 = (Graphics2D) g;
          g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
     
          if (drawQuizGraph) {
             g.drawString(" Quiz Averages", 10, 150);
          }
     
       }
     
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
     
       private class QuizButtonAction extends AbstractAction {
          public QuizButtonAction(String name) {
             super(name);
          }
     
          @Override
          public void actionPerformed(ActionEvent arg0) {
             drawQuizGraph = true;
             repaint();
          }
       }
     
       private static void createAndShowGui() {
          GUI3 mainPanel = new GUI3();
     
          JFrame frame = new JFrame("Graphs");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
     
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }

Similar Threads

  1. Resize an immage
    By gvgenop in forum Java Theory & Questions
    Replies: 2
    Last Post: October 28th, 2011, 01:06 PM
  2. (Javascript) Resize an image according to browser.
    By cybershadow in forum Other Programming Languages
    Replies: 3
    Last Post: October 13th, 2011, 11:24 AM
  3. Resize a window without native decorators
    By supertreta in forum AWT / Java Swing
    Replies: 0
    Last Post: January 11th, 2011, 02:06 PM
  4. [Swing-Progress Bar] Can't resize progress bar
    By Grabar in forum What's Wrong With My Code?
    Replies: 0
    Last Post: March 14th, 2010, 12:27 PM
  5. Difference between Speech API and Sound API
    By zeeshanmirza in forum Java SE APIs
    Replies: 1
    Last Post: October 22nd, 2009, 12:22 AM

Tags for this Thread