Ask your own question, for FREE!
Computer Science 17 Online
OpenStudy (anonymous):

Okay so I'm fairly new to java. I need help with a code where the programs reads in a txt file, and outputs the word, and how many times they appeared in the file. I want to output the result in a Window, I think its called JFrame. I figured out the code to get the words and number of times they appear on the console, need help with outputting in another frame.

OpenStudy (anonymous):

This is the code: { public static void main(String[] args) throws FileNotFoundException { // Read-in text from a file and store each word and its // frequency (count) in a collection. Scanner inputFile = new Scanner(new File("phrase.txt")); String word; Integer count; TreeMap<String,Integer> myMap = new TreeMap<String,Integer>(); while(inputFile.hasNext()) { word = inputFile.next(); count = myMap.get(word); if (count==null) { count=1; myMap.put(word,count); } else { count=count+1; myMap.put(word,count); } } inputFile.close(); // Output each word, followed by a tab character, followed by the // number of times the word appeared in the file. The words should // be in alphabetical order. for (String i: myMap.keySet()) { System.out.println(i+ "\t" + myMap.get(i)); } } }

OpenStudy (woodrow73):

If you want the output text in a frame that isn't necessarily a JFrame, you should consider JOptionPane's showMessageDialog() method, which is a simple one-liner. ie; ``` //import javax.swing.JOptionPane; String str = ""; for(int i = 1; i < 10; i++) { str += String.valueOf(i)+".\n"; } JOptionPane.showMessageDialog(null, str); //null for parentFrame will lead to a default created frame //str is the message to display ``` For usage of a JFrame, here's an example to help get you started: ``` //main frame JFrame jf = new JFrame("title"); //jf.setSize(500, 500); JPanel jp = new JPanel(); jp.setBackground(Color.BLACK); ArrayList<JLabel> toPrint = new ArrayList<JLabel>(); for(int i = 1; i < 6; i++) { toPrint.add(new JLabel("Entry "+String.valueOf(i))); toPrint.get(i-1).setForeground(Color.GREEN); toPrint.get(i-1).setBackground(Color.BLACK); } for(JLabel label : toPrint) { jp.add(label); } jf.add(jp); jf.pack(); //auto-sets the dimensions based on inner component sizes jf.setLocationRelativeTo(null); //sets frame to appear in center jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //close program after exit jf.setVisible(true); //show frame ``` To vertically align text in a Frame, I'd either use the above example with a GridLayout layout manager, or a JList, or a JTextArea.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!