Java School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a Java Expert!

Join 300,329 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,841 people online right now. Registration is fast and FREE... Join Now!




histogram

 

histogram, real time updates to a histogram

rgfirefly24

18 Apr, 2008 - 09:37 AM
Post #1

D.I.C Addict
Group Icon

Joined: 7 Apr, 2008
Posts: 527



Thanked: 17 times
Dream Kudos: 150
My Contributions
ok so i have the following code(it probably is really sloppy but i'll clean it up when i get it working.)
CODE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class lab4 extends JFrame {
    private JTextArea jta;
    private Histogram histogram = new Histogram();

    public lab4()
    {
        // Store text area in a scroll pane
        JScrollPane scrollPane = new JScrollPane(jta = new JTextArea());
        jta.setWrapStyleWord(true);
        jta.setLineWrap(true);
        jta.setPreferredSize(new Dimension(800,300));
        jta.setLayout(new GridLayout(2,1,1,1));




        add(scrollPane);

        jta.addKeyListener(new KeyAdapter() {
                  /** Handle the button action */
                  public void KeyPressed(KeyEvent e) {
                        // Count the letters in the text area
                        int[] count = countLetters();

                    // Set the letter count to histogram for display
                        histogram.showHistogram(count);


                  }
            });


        jta.add(histogram);
    }



    private int[] countLetters()
    {
        // Count for 26 letters
        int[] count = new int[26];

        // Get contents from the text area
        String text = jta.getText();

        text = text.toUpperCase();

        // Count occurrence of each letter (case insensitive)
        for (int i = 0; i < text.length(); i++)
        {
          char character = text.charAt(i);

          if ((character >= 'A') && (character <= 'Z'))
          {
            count[(int)character - 65]++; // The ASCII for 'A' is 65
          }
          }
          return count; // Return the count array
      }



    public static void main(String[] args) {
       lab4 frame = new lab4();
       frame.setLocationRelativeTo(null); // Center the frame
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setTitle("lab4");
       frame.setSize(800,600);
       frame.pack();
       frame.setVisible(true);

    }
}


here is the histogram code:
CODE
import javax.swing.*;
import java.awt.*;

public class Histogram extends JPanel {
  // Count the occurrence of 26 letters
  private int[] count;

  /** Set the count and display histogram */
  public void showHistogram(int[] count) {
    this.count = count;
    repaint();
  }

  /** Paint the histogram */
  protected void paintComponent(Graphics g) {
    if (count == null) return; // No display if count is null

    super.paintComponent(g);

    // Find the panel size and bar width and interval dynamically
    int width = getWidth();
    int height = getHeight();
    int interval = (width - 40) / count.length;
    int individualWidth = (int)(((width - 40) / 24) * 0.60);

    // Find the maximum count. The maximum count has the highest bar
    int maxCount = 0;
    for (int i = 0; i < count.length; i++) {
      if (maxCount < count[i])
        maxCount = count[i];
    }

    // x is the start position for the first bar in the histogram
    int x = 30;

    // Draw a horizontal base line
    g.drawLine(10, height - 45, width - 10, height - 45);
    for (int i = 0; i < count.length; i++) {
      // Find the bar height
      int barHeight =
        (int)(((double)count[i] / (double)maxCount) * (height - 55));

      // Display a bar (i.e. rectangle)
      g.drawRect(x, height - 45 - barHeight, individualWidth,
        barHeight);

      // Display a letter under the base line
      g.drawString((char)(65 + i) + "", x, height - 30);

      // Move x for displaying the next character
      x += interval;
    }
  }

  /** Override getPreferredSize */
  public Dimension getPreferredSize() {
    return new Dimension(300, 300);
  }
}


what this is sapposed to do is display an input field in the bottom which a user inputs random letters and in the top half it displays in bar graph form the amount of A's-Z's the user inputed

This post has been edited by rgfirefly24: 18 Apr, 2008 - 09:51 AM

User is offlineProfile CardPM
+Quote Post


pbl

RE: Histogram

18 Apr, 2008 - 11:14 AM
Post #2

Java Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 9,533



Thanked: 1123 times
Dream Kudos: 450
My Contributions
I don't say that it is not possible but I have never seen a JTextArea with a awt.Layout

Assuming it is possible (the compiler does not complain and there are no run time error)

OK now you have a JTextArea with a GridLayout on 2 rows ?

You have add(histogram) and what else ? What goes on the second row.

How does a JTextArea, with a layout of 2 rows, knows where to add (in which row to add) the characters typed ?

This seems compilcated to me but again I might be completly wrong.

Why don't you simply set your JFrame with a GridLayout(2,1,1,1);
- add to the frame the JTextArea in its JScrollPane
- add the histogram

Then you will have your JTextArea in first row and your histogram in the second row.

I mean I don't see any sens of adding the JPanel where you draw into a JTextArea.

Also what you want is a KeyListener not a KeyAdapter
you will have to implement the 3 methods:

CODE

        jta.addKeyListener(new KeyListener() {
                  /** Handle the button action */
                  public void keyPressed(KeyEvent e) {
                        // Count the letters in the text area
                        int[] count = countLetters();

                    // Set the letter count to histogram for display
                        histogram.showHistogram(count);
                  }

    public void keyReleased(KeyEvent e) {
    }
    public void keyTyped(KeyEvent e) {                
    }
            });


and the name of the method is keyPressed not KeyPressed (capital K).

This kind of work
java

public lab4()
{
setLayout(new GridLayout(2,1,1,1));
// Store text area in a scroll pane
jta = new JTextArea();
JScrollPane scrollPane = new JScrollPane(jta);
jta.setWrapStyleWord(true);
jta.setLineWrap(true);
jta.setPreferredSize(new Dimension(800,300));

add(scrollPane);

jta.addKeyListener(new KeyListener() {
/** Handle the button action */
public void keyPressed(KeyEvent e) {
// Count the letters in the text area
int[] count = countLetters();

// Set the letter count to histogram for display
histogram.showHistogram(count);
}

public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}
});


add(histogram);
}


Hope this help... I am anxious to see your solution.

This post has been edited by pbl: 18 Apr, 2008 - 11:23 AM
User is offlineProfile CardPM
+Quote Post

rgfirefly24

RE: Histogram

18 Apr, 2008 - 12:31 PM
Post #3

D.I.C Addict
Group Icon

Joined: 7 Apr, 2008
Posts: 527



Thanked: 17 times
Dream Kudos: 150
My Contributions
I works beautifully thanks. Although the histogram is on the bottom and the scrollpane is on the top. Is there any way to flip them?

otherwise changing keyadapter(i cant believe i even used this...... headsmack) to keylistener was the key

new code(that works)

CODE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class lab4 extends JFrame {
    private JTextArea jta = new JTextArea();
    private Histogram histogram = new Histogram();


      // Create a new frame to hold the histogram panel
     private JPanel histogramFrame = new JPanel();

        public lab4()
        {
            setLayout(new GridLayout(2,1,1,1));
            // Store text area in a scroll pane
            JTextArea jta;
            JScrollPane scrollPane = new JScrollPane(jta = new JTextArea()); //had to put this here otherwise -1 pt out of 10.... hard nosed teachers><
            jta.setWrapStyleWord(true);
            jta.setLineWrap(true);
            jta.setPreferredSize(new Dimension(800,300));

           add(scrollPane);

           jta.addKeyListener(new KeyListener() {
                     /* Handle the button action */
                     public void keyPressed(KeyEvent e) {
                         // Count the letters in the text area
                           int[] count = countLetters();

                       // Set the letter count to histogram for display
                           histogram.showHistogram(count);
                     }

       public void keyReleased(KeyEvent e) {
          
       }
       public void keyTyped(KeyEvent e) {
          
       }
               });


           add(histogram);
       }



    private int[] countLetters()
    {
        // Count for 26 letters
        int[] count = new int[26];

        // Get contents from the text area
        String text = jta.getText();

        text = text.toUpperCase();

        // Count occurrence of each letter (case insensitive)
        for (int i = 0; i < text.length(); i++)
        {
          char character = text.charAt(i);

          if ((character >= 'A') && (character <= 'Z'))
          {
            count[(int)character - 65]++; // The ASCII for 'A' is 65
          }
          }
          return count; // Return the count array
      }



    public static void main(String[] args) {
       lab4 frame = new lab4();
       frame.setLocationRelativeTo(null); // Center the frame
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setTitle("lab4");
       frame.setSize(800,600);
       frame.pack();
       frame.setVisible(true);

    }
}

User is offlineProfile CardPM
+Quote Post

pbl

RE: Histogram

18 Apr, 2008 - 12:46 PM
Post #4

Java Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 9,533



Thanked: 1123 times
Dream Kudos: 450
My Contributions
QUOTE(rgfirefly24 @ 18 Apr, 2008 - 01:31 PM) *

I works beautifully thanks. Although the histogram is on the bottom and the scrollpane is on the top. Is there any way to flip them?


Kind of obvious: change the order into which you add your components to the frame
Replace:

add(scrollPane);
....
add(histogram);

by:

add(histogram);
...
add(scrollPane);
User is offlineProfile CardPM
+Quote Post

rgfirefly24

RE: Histogram

18 Apr, 2008 - 12:56 PM
Post #5

D.I.C Addict
Group Icon

Joined: 7 Apr, 2008
Posts: 527



Thanked: 17 times
Dream Kudos: 150
My Contributions
QUOTE(pbl @ 18 Apr, 2008 - 01:46 PM) *

QUOTE(rgfirefly24 @ 18 Apr, 2008 - 01:31 PM) *

I works beautifully thanks. Although the histogram is on the bottom and the scrollpane is on the top. Is there any way to flip them?


Kind of obvious: change the order into which you add your components to the frame
Replace:

add(scrollPane);
....
add(histogram);

by:

add(histogram);
...
add(scrollPane);


thanks again... I am so tired right now in my last weeks of classes learning 4 different languages at once and its all just blurring together. i will never attempt to learn Java, VB.Net, C#, and ASP.Net with AJAX in the same semester again.
User is offlineProfile CardPM
+Quote Post

m2s87

RE: Histogram

18 Apr, 2008 - 03:45 PM
Post #6

D.I.C Regular
Group Icon

Joined: 28 Nov, 2006
Posts: 390



Thanked: 15 times
Dream Kudos: 1225
My Contributions
QUOTE
thanks again... I am so tired right now in my last weeks of classes learning 4 different languages at once and its all just blurring together. i will never attempt to learn Java, VB.Net, C#, and ASP.Net with AJAX in the same semester again.


Java is ~ same as C#, C#.Net IS SAME AS VB.Net(well minor differences), ASP.Net is ~ same to VB.Net as Java is to .jsp or servlet. And well Ajax is just javascript and json/xml. Well thy should be blurred together, thy are not all that different.
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/7/09 03:50PM

Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month