Violet_82 89 Posting Whiz in Training

Ah OK, crystal clear for the columns/rows now, thanks for that!
For resizing, OK so no need to use dimension then, still a bit confused though, sorry. Let's see i I understood.

Text components typically have constructors or set methods in chars/lines

So technically, I've already done this when I created the text areas:

textInput = new JTextArea(10,12);//holds the input text
        textOutput = new JTextArea(10,15);//hold the output text

JLabel and Jbutton though don't seem to have any constructor in the API that allows to enter any size

Violet_82 89 Posting Whiz in Training

HI, sorry for the late reply, I was on the road as well, but no access to internet.
Right, maybe I did misunderstood the whole thing then, I don't know. My understanding is that gridwidth and gridheight set the height and the width of the component. Why would a height of 2 mean overlapping with wathever below? I would have thought it meant only for the component to span 2 rows rather than 1 and whatever is below gets pushed down. There is nothing about overlapping in the API, well not that I could see.
As for the text area, the height is 3 because I would have thought, again, that it would span 3 rows, pushing down whatever is below. This was my itnerpretation of http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
What's the real explanation :-)? Meaning, when would you want the height to be 1 and when not?
I've made some changes to the constraints:

add(instructions, new GridBagConstraints(0,0,2,1,0,0,CENTER,HORIZONTAL, new Insets(10,15,10,15),0,0));//adding instruction jlabel and constraints
        //shouldn't grow vertically, where is the padding on the left
        add(new JScrollPane(textInput), new GridBagConstraints(0,1,2,1,0.5,0.5,CENTER,BOTH,new Insets(10,15,10,15),10,10));//adding textInput and constraints
        add(processButton, new GridBagConstraints(0,2,1,1,1.0,1.0,CENTER,HORIZONTAL,new Insets(10,15,10,15),1,1));//adding processButton and constraints
        add(clearButton, new GridBagConstraints(1,2,1,1,1.0,1.0,CENTER,HORIZONTAL,new Insets(10,15,10,15),1,1));//adding clearButton and constraints
        add(new JScrollPane(textOutput), new GridBagConstraints(0,3,2,1,0.5,0.5,CENTER,BOTH,new Insets(10,15,10,15),1,1));//adding textOutput   

and the layout looks a tad better, in the sense that the components are not overlapping anymore (I've reduced the height of the textAreas to 1, the height of the buttons to 1 as well, changed the fill property to horizontal for the buttons, …

Violet_82 89 Posting Whiz in Training

Just an idea, would it make any different if I arrange components in separate panels rather than having them to sit inside the JFrame directly?

Violet_82 89 Posting Whiz in Training

Thanks. So I played around with the values a little and also made some changes to the insets of the textAreas, just to create a bit more space. For the weightx and weighty instead, I eventually set the ones for the textArea both at 0.5 and the ones for both buttons at 1.00, but still no joy. If I understand things correctly the weight controls the extra space allocated when resized, but when I resize, all the space seems to be going to the JLabel instead (which has weightx set to 0 and weighty set to 1.0.)
The amendments to the insets of the textareas though allowed me to see exactly what goes on in the GUI, even though I don't quite understand it: it looks like the buttons are huge and sitting behind the textArea?! see screenshot. I hadn't found anywhere reference to the fact that a component can sit behind another one.
Also, how do I make the whole windows the size I want it to be? As mentioned previously I have it set at wordCount.setSize(900,800); but the real size of the GUI isn't the one specified, it's much smaller and I'm not quite sure where it's taking its size from.
Here is the GUI window as it comes up when I launch the application
wordCountGBL_error_1.jpg
and here is the resized GUI instead:
wordCountGBL_error_1_resized.jpg

Violet_82 89 Posting Whiz in Training

Oh cool, glad I got my first Java suggestion right :-)!

Violet_82 89 Posting Whiz in Training

I noticed that because sometimes I start a post directly from the home page, not sure if other people do that. So there won't be a fix for that I seem to undestand, just wondering :-)

Violet_82 89 Posting Whiz in Training

True, but if you select case 5, the program runs once more and then after that it exits. I would have used a while loop rather than a do-while. Maybe, but more expert members might be able to tell you more, the condition 'choice' is evaluated at the beginning, so when you select 5 and reach the end of the loop (while(choice!= 5);) choice isn't evaluated again, that's why I'm saying, maybe you want to use a while loop. But wait for somebody else to confirm this, as I may be wrong

Violet_82 89 Posting Whiz in Training

Hi ddanbe, I wouldn't bring it to a computer shop as I can do it myself :-). The warranty has expired. Anyway, I bought the part on ebay in the end as Dell are pretty slow to reply and I can't wait for them to come back to me. It should arrive in a couple of days, it looked like the part I needed.

Violet_82 89 Posting Whiz in Training

Hi, can somebody tell me why, when posting a question rather than a thread, the attachment icon isn't there? See attachment:
iconMissing.jpg

Violet_82 89 Posting Whiz in Training

HI guys, as mentioned in my revious post, I'll redo my wordCount application using the GridBagLayout approach. The functionality of the application hasn't changed at all: I've only removed the various Jpanels and, for simplicity, used only the JFrame and attached all the comonents to the JFrame.
I've had a look around to see how the GridBagLayout works etc, and even if I've seen slightly different approaches, I went for the most concise of them all where I create the component, add it to the panel using this constructor (found here https://docs.oracle.com/javase/8/docs/api/java/awt/GridBagConstraints.html)

GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill, Insets insets, int ipadx, int ipady)

I started with photoshop first, drawing roughly how I'd like the application to look like:
wordCountGBL.jpg
So I began to position my components in a 4x2 grid, but I run into problems, and quite a few. Here is the code that sets the constraints:

add(instructions, new GridBagConstraints(0,0,2,1,0,1.0,CENTER,BOTH, new Insets(1,1,1,1),1,1));//adding instruction jlabel and constraints
    add(new JScrollPane(textInput), new GridBagConstraints(0,1,2,2,1.0,1.0,CENTER,BOTH,new Insets(1,1,1,1),1,1));//adding textInput and constraints
    add(processButton, new GridBagConstraints(0,2,1,2,0,0,CENTER,BOTH,new Insets(1,1,1,1),1,1));//adding processButton and constraints
    add(clearButton, new GridBagConstraints(1,2,1,2,0,0,CENTER,BOTH,new Insets(1,1,1,1),1,1));//adding clearButton and constraints
    add(new JScrollPane(textOutput), new GridBagConstraints(0,3,2,3,1.0,1.0,CENTER,BOTH,new Insets(1,1,1,1),1,1));//adding textOutput       

Somehow, only the JLabel and the two JTextAreas are visible, the two buttons aren't there. This is how it looks like:
wordCountGBL_problems.jpg
The code seems to me to be OK, in the sense that I've positioned the buttons one next …

Violet_82 89 Posting Whiz in Training

Oh, I forgot, here is the final code:

/*WordCount.java
Application determines how many times a word has occurred in the text given
*/
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JScrollPane;
import java.awt.Insets;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.StringTokenizer;
public class WordCount extends JFrame{
    private JPanel buttonsPanel;
    private JPanel topPanel;
    private JTextArea textInput;
    private JTextArea textOutput;
    private JButton processButton;
    private JButton clearButton;
    private JLabel instructions;
    private BorderLayout frameLayout;
    private BorderLayout topPanelLayout;
    private GridLayout buttonsPanelLayout;
    private String stringToTest;//holds string pasted in textarea
    private String[] tokens;//array of tokenized strings
    Map<String,Integer> mp = new HashMap<String, Integer>();//declaring a map object
    //constructor
    public WordCount(){
        super("Word count application");
        buttonsPanel = new JPanel();//holds the two buttons
        topPanel = new JPanel();//holds the textArea and jlabel
        textInput = new JTextArea(10,15);//holds the input text
        textOutput = new JTextArea(10,15);//hold the output text
        stringToTest = "";//initialize to empty string
        processButton = new JButton("Count");//action abutton
        clearButton = new JButton("Clear");//to clear textArea
        instructions = new JLabel("Copy and paste text in the below text area, click Count to count the words.\n");//holding instructions
        BorderLayout frameLayout = new BorderLayout();//for JFrame
        BorderLayout topPanelLayout = new BorderLayout();//for top level panel
        GridLayout buttonsPanelLayout = new GridLayout(1,2,5,5);//for buttons       
        setLayout(frameLayout);//set layout of Frame
        topPanel.setLayout(topPanelLayout);//set topPanel layout
        topPanel.add(instructions, BorderLayout.NORTH);//add JLabel to topPanel
        instructions.setOpaque(true);//need this to be able to change the colour
        instructions.setBackground(Color.CYAN);     
        topPanel.add(new JScrollPane(textInput), BorderLayout.CENTER);//add textInput to topPanel
        buttonsPanel.setLayout(buttonsPanelLayout);//set buttonsPanel layout
        buttonsPanel.add(processButton);//add processButton to panel
        buttonsPanel.add(clearButton);//add clearButton to panel        
        add(topPanel, BorderLayout.NORTH);//add topPanel to JFrame
        add(buttonsPanel, …
Violet_82 89 Posting Whiz in Training

Cool, then GBL will be. I do understand what you say about not making things unnecessarily complicated though, but it will have a chance to practice :-)

Violet_82 89 Posting Whiz in Training

OK, I understand, I'll try to apply those principles in the next application then.
About the GridBagLayout: the reason why I was thinking to redo this application with a GridBagLayout is because, as mentioned, I'm not satisfied with the way I display buttons and textfields
wordCount.jpg
I wanted some space between the top panel, the buttons and the bottom panel; I also wanted some padding in the JLabel, and add space outside the elements - like between the textarea and the edge of the bounding box, and I would have thought that with the GridBagLayout I could achieve all that, but if you think that I can do all that with the current layouts I've used or by rejigging the panels and the elements inside them, then I'm happy to redo it. I had a look on google a few days ago and a few people seem to say that you can use transparent borders, some other saying that the space/padding can be created by using other layoutManagers so I'm not quite sure what to do. I seem to remember testing margins (setMargin()) but it only worked inside the textarea rather than outside.
I've also read a few tutorials online, but none of them seems to be giving a definitive answer as to how to create empty space/padding around elements/panels

Violet_82 89 Posting Whiz in Training

That's fair enough, I like the way you guys work, and yes you're right, better a hint than giving away code, my bad for misunderstanding and not spotting a silly mistake as that.
In any case, on a positive note, from now on, I will do the GUI as last thing and not as first, lesson learned. Do you guys think that for every GUI I develop I have to do a console-only version first, to get the logic right, and then only when the functionality works, redo the program as a GUI? That seems like quite a bit of overhead though. Is there any other way you recommend?
Finally, I will attempt to redo this application with a GridBagLayout, as you JamesCherrill said that that 's the most powerful and customizable layout manager and with the ones I've used I'm really not happy with the result, but this will go into a new thread.

Violet_82 89 Posting Whiz in Training

Sorry, I didn't mean to ignore it, more likely I didn't understand your reply.
So you're saying there are two instances of textInput: is that because the second time I prefixed it with the type JTextArea effectively shadowing the private variable? If so, sorry I didn't realize that by doing it I'd create another variable. In that case I have a duplicate of all the private variables, without realizing. I will amend.

Violet_82 89 Posting Whiz in Training

Thank JamesCherrill, yes correct, I would have thought that the constructor initialized the variable to a default state. Anyway, I've now "initialised" both textInput and textOutput, but since they are JTextArea I initialized them to empty, like so

textOutput.setMargin(new Insets(5,5,5,5));//sets margins inside the element
        textInput.setMargin(new Insets(5,5,5,5));//sets margins inside the element
        textInput.setText(" ");//initialize to empty string
        textOutput.setText(" ");//initialize to empty string
        ProcessButtonHandling handler1 = new ProcessButtonHandling();
        ClearButtonHandling handler2 = new ClearButtonHandling();

Trouble is, I still get the same errors, and the line that appears in the stack trace refers to line 76 now (it was 74 before) which is this stringToTest = textInput.getText();
As far as I know stringToTest is declared private String stringToTest;//holds string pasted in textarea, initialized stringToTest = "";//initialize to empty string and put to use processString(getString());//call function to split string (there is of course a getter method

public String getString(){
        return stringToTest;
    }

)
is it possible that perhaps the stringToTest variable somehow doesn't get the text that's in the textArea and therefore the functions calls inside the actionPerformed method can't process the text?

public void actionPerformed(ActionEvent event){
            stringToTest = textInput.getText();
            processString(getString());//call function to split string
            mapWords();//count words and place results in the hashmap
            printMap();//print the map values and keys in the textArea
        }//end of actionPerformed

Here is the full class again, with the amendments (this time on pastebin) http://pastebin.com/8wCe9E2S

Violet_82 89 Posting Whiz in Training

I prefer to do everything online. Managed to get hold of Dell, not sure if dell US or UK though, they said they'll help me to find the exact part...will see, if it drags on too long I'll get that off ebay
cheers

Violet_82 89 Posting Whiz in Training

Right, OK, so I've implemented the GUI now with the logic of the console application, but I'm still facing the same errors (I haven't implemented the clear button as yet, I was working on the Count button first).
Here are the two new files:

/*WordCount.java
Application determines how many times a word has occurred in the text given
*/
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JScrollPane;
import java.awt.Insets;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.StringTokenizer;
public class WordCount extends JFrame{
    private JPanel buttonsPanel;
    private JPanel topPanel;
    private JTextArea textInput;
    private JTextArea textOutput;
    private JButton processButton;
    private JButton clearButton;
    private JLabel instructions;
    private BorderLayout frameLayout;
    private BorderLayout topPanelLayout;
    private GridLayout buttonsPanelLayout;
    private String stringToTest;//holds string pasted in textarea
    private String[] tokens;//array of tokenized strings
    Map<String,Integer> mp = new HashMap<String, Integer>();//declaring a map object
    //constructor
    public WordCount(){
        super("Word count application");
        JPanel buttonsPanel = new JPanel();//holds the two buttons
        JPanel topPanel = new JPanel();//holds the textArea and jlabel
        JTextArea textInput = new JTextArea(10,15);//holds the input text
        JTextArea textOutput = new JTextArea(10,15);//hold the output text
        stringToTest = "";//initialize to empty string
        JButton processButton = new JButton("Count");//action abutton
        JButton clearButton = new JButton("Clear");//to clear textArea
        JLabel instructions = new JLabel("Copy and paste text in the below text area, click Count to count the words.\n");//holding instructions
        BorderLayout frameLayout = new BorderLayout();//for JFrame
        BorderLayout topPanelLayout = new BorderLayout();//for top level panel
        GridLayout buttonsPanelLayout = new GridLayout(1,2,5,5);//for buttons       
        setLayout(frameLayout);//set …
Violet_82 89 Posting Whiz in Training

Oh I see, that's because the method get() returns the value and not the key! I got it!

No need to have an if test for whether the entry exists or not.

Definitely nicer in Java 8 :-)!
OK, so I'll move on and build the GUI then. I divided everything in functions so hopefully it will be easy to call the right one at the right time. Will post back when I get the GUI working.

Violet_82 89 Posting Whiz in Training

I went for it and implemented the pseudocode (sorry I asked about the pseudocode in case I was completely off). Anyway, here is the final code, and it all seems to work, even if there is one thing that really bothers me. Let's look at the code first (the WordCountTest.java file is the same as before so I haven't included it):

/*WordCount.java
Application determines how many times a word has occurred in the text given
*/
//for the map
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.StringTokenizer;
public class WordCount{
    private String stringToTest;
    private String[] tokens;
    Map<String,Integer> mp = new HashMap<String, Integer>();//declaring a map object
    //constructor
    public WordCount(){
        stringToTest = "This is the string I want to test, and I'm curious to see what the result is as I'm curious.";
        processString(getString());//call function to split string
        mapWords();//count words and place results in the hashmap
        printMap();//print the map values and keys
    }//end of constructor   
    public String getString(){
        return stringToTest;
    }
    public void printInfo(){
        System.out.printf("%s ", getString());
    }

    public void processString(String testingString){        
        //String[] tokens = testingString.split("(?=[,.])|\\s+");
        testingString = testingString.replaceAll("[,.;:]","");//remove the characters in brackets and replace them with nothing
        tokens = testingString.split(" ");//split string using space as delimiter
        System.out.printf("Number of elements: %d\nTokens are \n", tokens.length);
        //print to test
        for(String token : tokens){
            System.out.println(token);
        }       
    }
    public void mapWords(){
        for(int i = 0; i < tokens.length; i++){
            if(mp.containsKey(tokens[i])){
                //increment Integer
                mp.put(tokens[i], mp.get(tokens[i]) + 1);//add it to the hashmap and increment integer
            } 
            else{
                mp.put(tokens[i],1);//add it to the hashmap
            }
        }
    }
    public void …
Violet_82 89 Posting Whiz in Training

Hi guys OK so I've done some work and made some changes to your code as well Tywin, hope that's OK, but I'm a bit unsure as to how to count words with the hashmap. Let's see first what I've done so far: the application is now a console one, it creates a string, removes ",.:;" and splits it into an array using space as delimiter:

/*WordCount.java
Application determines how many times a word has occurred in the text given
*/
//for the map
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.StringTokenizer;
public class WordCount{
    private String stringToTest;
    Map<String,Integer> mp = new HashMap<String, Integer>();//declaring a map object
    //constructor
    public WordCount(){
        stringToTest = "This is the string I want to test, and I'm curious to see the results.";
        processString(getString());//call function to split string
    }//end of constructor   
    public String getString(){
        return stringToTest;
    }
    public void printInfo(){
        System.out.printf("%s ", getString());
    }

    private void processString(String testingString){       
        //String[] tokens = testingString.split("(?=[,.])|\\s+");
        testingString = testingString.replaceAll("[,.;:]","");//remove the characters in brackets and replace them with nothing
        String[] tokens = testingString.split(" ");//split string using space as delimiter
        System.out.printf("Number of elements: %d\nTokens are \n", tokens.length);
        //print to test
        for(String token : tokens){
            System.out.println(token);
        }

    }
}//end of WordCount class



/*WordCountTest.java
    WordCountTest to test the class
*/

public class WordCountTest{
    public static void main(String[] args){
        WordCount wordCount = new WordCount();  
        wordCount.printInfo();
    }
}//end of WordCountTest

Now I have to use the hashmap to count the words. Here is some pseudocode, is this a good approach?

loop thru strings …
Violet_82 89 Posting Whiz in Training

OK thanks for the feedback guys. Scrap all the code I've done, I'm starting from scratch with a console app and trying to do what you say.
Self-learn it Taywin I'm afraid. Sooner or later I should start following the good practice, so let's start now. I'll come back with some code soon
thanks

Violet_82 89 Posting Whiz in Training

Hi guys, I have a dell xps 17 and the connector is broken. I've found what I need on ebay http://www.ebay.co.uk/itm/DELL-XPS-17-L701X-L702X-POWER-SOCKET-JACK-CABLE-RMD72-R7DCGM7PB000-PJC237-/271230139718?clk_rvr_id=932028979691&rmvSB=true but I was wondering if anybody knows whether an official dell retailer exists. I had a look at their site but I couldn't find the part, I also live in the UL so if dell has it, they will have to ship it to the UK. ANy idea?

Violet_82 89 Posting Whiz in Training

hi stultuske, I have this tendency of developing the GUI first...sorry, it's that I don't know how to test that the buttons are working if the GUI isn't there really...in anycase, if you let me know how I can test my appplication without GUI and that helps, more than happy to do it.
What I can say is that the GUI does work because I tested it, and if I remove the

textInput.setText(" ");
textOutput.setText(" ");

from the event handling class, I get no errors

private class ClearButtonHandling implements ActionListener{
        public void actionPerformed(ActionEvent event){
            textInput.setText(" ");
            textOutput.setText(" ");
        }//end of actionPerformed
    }//end of inner class

I thought it might have been a problem with scope, but the textInput and textOutput are declared private, the constructor position them where they should be and initialize them to be empty and the actionPerformed() method empties them again when needed

Violet_82 89 Posting Whiz in Training

Right, I quickly knocked off something, and soon run into troubles. The GUI is set up - although I've decided that I will redo it later with a GridBagLayout as I don't seem to be able to display things the way I want, especially when it comes to add padding etc. I say "later" because I would like to get the whole thing to work first, know that it works and then mess around with it.
wordCount.jpg
Here is the code and then then I'll explain the issue:

 /*WordCount.java
Application determines how many times a word has occurred in the text given
*/
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import javax.swing.JScrollPane;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
public class WordCount extends JFrame{
    private JPanel buttonsPanel;
    private JPanel topPanel;
    private JTextArea textInput;
    private JTextArea textOutput;
    private JButton processButton;
    private JButton clearButton;
    private JLabel instructions;
    private BorderLayout frameLayout;
    private BorderLayout topPanelLayout;
    private GridLayout buttonsPanelLayout;
    //constructor
    public WordCount(){
        super("Word count application");
        JPanel buttonsPanel = new JPanel();//holds the two buttons
        JPanel topPanel = new JPanel();//holds the textArea and jlabel
        JTextArea textInput = new JTextArea(10,15);//holds the input text
        JTextArea textOutput = new JTextArea(10,15);//hold the output text
        JButton processButton = new JButton("Count");//action abutton
        JButton clearButton = new JButton("Clear");//to clear textArea
        JLabel instructions = new JLabel("Copy and paste text in the below text area, click Count to count the words.\n");//holding instructions
        BorderLayout frameLayout = new BorderLayout();//for JFrame
        BorderLayout topPanelLayout = new …
Violet_82 89 Posting Whiz in Training

eh eh, noticed you haven't mentioned them :-). I'll get coding and post the results here as soon as I have something

Violet_82 89 Posting Whiz in Training

Thanks.

Best create a separate handler class per button (unless the buttons have very similar functionality).

Flicking through some code examples in the book, I can see that maybe, what you suggested, is better achieved with anonymous classes rather than named classes. WOuld it be better if I use those do you think?

As to the counting, traditional mechanism would use a HashMap<String, Integer>

OK, no problem, I've used it before. Spo presumably I'll do what I've mentioned before (array and split to deal with the text) and then populate the HashMap with the words (key) and the number of occurences (values). Did I understand it correctly?

Violet_82 89 Posting Whiz in Training

HI guys,
I'm trying to build a small GUI application where users can input text (in a JTextArea) and by pressing a button, you get a summary of how many times each word in the text has occurred.
So here come the questions.
First, the GUI itself. The way I envisage it to be built is with a JLabel on the top, explaining briefly what the application is about, JTextArea holding the text to process, another JTextArea to hold the results, a JPanel with two buttons, a "process button" to kick things off and let the application count the words in the text and a "clear" button which clears both JTextAreas.
Something like this:

-JFrame (default BorderLayout)
    -JPanel griBagLayout(positioned North)
        -JLabel 
        -JTextArea for sample text
    -JPanel griBagLayout (positioned Center)
        -JButton to process
        -JButton to clear first JTextArea
    -JTextArea for result (positioned South)

As far as the functionality is concerned instead, I was thinking to have a named handler class with a constructor taking a false or true parameter to determine which button is being pressed and act as a consequence of that: if the parameter is true, then it's the clear button, therefore clear everything, if true is the process button. So, something like this:

 ...
    clearButton.addActionListener(new ButtonHandler(true));
    processButton.addActionListener(new ButtonHandler(false));
    ...

Is that a good way to distinguish the buttons?

Finally, the functionality to process the text. I want to be able to process a lot of text, not just a few sentences. …

Violet_82 89 Posting Whiz in Training

Right, very odd. The reason why I started a new thread was because I couldn't really save anything on that USB and kept getting that "format message". I reformat that again in exFAT and now I managed to save something on it, so the message doesn't come up anymore. Weird.
@Gribouillis I tried to format it to NTFS but it just won't do it.

Violet_82 89 Posting Whiz in Training

Guys, I’m having a lot of problems with my 64GB usb stick.
It worked fine till somehow I think I formatted in exFAT format (that happened in Ubuntu as I was trying to install something on it and I formatted it using I can’t quite remember which utility in Ubuntu), and that’s when the nightmare begun. Every time I’d insert that into the USB port I’d get a “USB needs to be formatted” message. So, I first of all tried to format that from exFAT to NTFS, and I almost managed (in Windows using the format F: /fs:NTFS command): it took about a day but when it reached the end at 100% there was an error message saying something about not being able to create a proper file system (sorry I don’t remember the exact words).
Anyway, I also tried to format that to FAT (in windows) running the following command:
Format F: /fs:FAT32 but I got this error:

F:\>format F: /fs:FAT32
Insert new disk for drive F:
and press ENTER when ready...
The type of the file system is EXFAT.
The new file system is FAT32.
Verifying 64000M
Format cannot run because the volume is in use by another
process.  Format may run if this volume is dismounted first.
ALL OPENED HANDLES TO THIS VOLUME WOULD THEN BE INVALID.
Would you like to force a dismount on this volume? (Y/N) y
Volume dismounted.  All opened handles to this volume are now invalid.
123146240 bad sectors were encountered …
Violet_82 89 Posting Whiz in Training

OK, so it's definitely ignored by the forum correct?

Violet_82 89 Posting Whiz in Training

OK, thanks

Violet_82 89 Posting Whiz in Training

Here is the source code. Other beginners might find this useful, who knows.

 /*TouchType.java*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Dimension;//for setting the dimensions of a component
//import javax.swing.BorderFactory;//to set the borders
import java.awt.Insets;
//import java.awt.FlowLayout;
import javax.swing.JLabel;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import static java.awt.event.KeyEvent.*;//needed for the key constants
import javax.swing.JScrollPane;
//for the map
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;   
public class TouchType extends JFrame{
    //private JPanel mainPanel;//wrapping panel
    private String character;
    private int theChar;
    private JButton buttonToHighlight;//button to hightlight when the corresponding one is clicked
    private JPanel labelPanel;//panel for labels
    private JLabel label1;//first label
    private JLabel label2;//second label
    private JPanel keysPanel;//holding the keys
    private JButton newButton;
    //rows panels for keys. 5 rows.
    private JPanel row1;
    private JPanel row2;
    private JPanel row3;
    private JPanel row4;
    private JPanel row5;
    private JTextArea textArea;//text area
    private BorderLayout bLayout1;
    private BorderLayout bLayout2;
    private GridLayout keysPanelLayout;
    private GridLayout gridLayoutRow1;
    private GridLayout gridLayoutRow2;
    private GridLayout gridLayoutRow3;
    private GridLayout gridLayoutRow4;
    private GridLayout gridLayoutRow5;
    private Color originalColour;


    Map<Integer,JButton> mp = new HashMap<Integer,JButton>();//declaring a map object 

    public TouchType(){//constructor
        super("Typing application");    

        //creating JPanels
        labelPanel = new JPanel(); //panel for labels
        character = " ";
        keysPanel = new JPanel();//panel wrapper for key rows
        row1 = new JPanel();//panel for row1
        row2 = new JPanel();//panel for row2
        row3 = new JPanel();//panel for row3
        row4 = new JPanel();//panel for row4
        row5 = new JPanel();//panel for row5

        //creating a button and adding it to the appropriate JPanel
        row1.add(createButton(VK_DEAD_TILDE, "~"));     
        row1.add(createButton(VK_1, "1"));      
        row1.add(createButton(VK_2, "2")); …
Violet_82 89 Posting Whiz in Training

OK, will do that then. Out of interest though, are .java files allowed? And is there an official list of allowed types?

Violet_82 89 Posting Whiz in Training

Hardly illegal, but, at least in th UK, it might void your warranty. I personally unlock them myself (unless it's an iphone of course, in which case I have no idea how to do it). Try to unlock it yourself, you'll see it's not too hard after all...

Violet_82 89 Posting Whiz in Training

Hi guys, are we allowed to upload .java files to posts on the forum? the file uploader says not allowed, but I couldn't find the allowed/not allowed list of files anywhere/
thanks

Violet_82 89 Posting Whiz in Training

Understood, thanks. I may or may not redo this in GridBagLayout, not sure, will see if I have time to do that or move on with something else.
In any case, thanks ever so much for all your help and advices with this and for your patience, I've learned a lot by doing this exercise.

Violet_82 89 Posting Whiz in Training

That works perfectly, and yes with just one line of code as you said, brilliant! I did read your post carefully :-), I think I simply didn't understand, my apologies, I didn't realize that by

The only sensible way to get the correct character displayed is to use the KEY-TYPED event

you meant to get the unicode value, my bad.
About the layout, I have done a bit of reading here and there, especially when it comes to size of the components etc. I've come across a Dimension and an Insets classes. I used the insets to give some padding to the textArea, which worked really well:
textArea.setMargin(new Insets(15,5,15,5));//sets margins inside the element
and then attempted to modify the size of the buttons with setMinimumSize() (I first tried to change them all, just to see if that works, and if that worked, then I'd target each button as needed, but alas it got me nowhere, nothing changed at all - I tried also setMaxSize but no joy:)

for(JButton currentButton:mp.values()){
            currentButton.addKeyListener(handler);
            originalColour = currentButton.getBackground();
            Dimension minimumSize = new Dimension(100,100);
            currentButton.setMinimumSize( minimumSize );

There seems to be a lot of discussions online about changing size of components by changing the layout manager, which, ideally, I wouldn't want to do.
Finally I came across a method called setPreferredSize(), on a post on stackoverflow. That seems to be doing something, as in when I use it the size of the buttons does change, so I think I'll play …

Violet_82 89 Posting Whiz in Training

OK no problem, will use the keyTyped then.
Let's see if this is correct. KeyPressed will only get the constant of the button pressed on the actual keyboard, find the button in the map and change the color:

public void keyPressed(KeyEvent event){
            theChar = event.getKeyCode();           
            buttonToHighlight = mp.get(theChar);        
            buttonToHighlight.setBackground(Color.GREEN);
        }

keyTyped will work out which key it is and get it displayed on the textArea. I had a look at this keyTyped method and it seems that it only gets called if the key pressed isn't an action key, so I don't need to worry about those. Still i seems like I still need the switch statement to filter through space, enter and backspace keys, so make sure that the text "Enter", "Space" and "backspace" aren't added to the textArea. That's at least what happened when I removed the switch statement. I've also noticed that characters like "[", "]", ";", "/" print respectively "bracketClose", "bracketOpen", "comma", "semicolon", "slash". Does it mean that I have to add these cases in the switch too?

public void keyTyped(KeyEvent event){
            //String temp = KeyEvent.getModifiersText(event.getModifiers)
            switch(theChar){
                case VK_SPACE:
                    character += " ";
                    break;
                case VK_BACK_SPACE:             
                case VK_ENTER:              
                    character += "";
                    break;
                default:
                    character += String.format("%s", KeyEvent.getKeyText(theChar));//get the constant
            }
            textArea.setText(character);
        }

Method keyReleased finally.

You need to use the VK in the key released event to know which key to un-highlight.

I understand the scenario you provided and how we may not know which button needs to have its background …

Violet_82 89 Posting Whiz in Training

I think you're right, I meant setFocusable(true), apologies.
You're right, I'm leaving the keyTyped out of the equation. Not that I don't think it's a good way to do it of course, I mean, I know for a fact that you're 100% right when you suggested that, but having seen that there is a perhaps (at least in my eyes of beginner) simpler way to sort things out I thought I'd try and it seems like that keyTyped isn't essential to get the character printed on the textArea. I understood what you said about it though and I do understand now the difference between the three types of events, it just seems to me that not all of them need to be used to achieve what I'm trying to achieve.
I had a go at it, and I think I sorted it, in a way that I seem to have got rid of the focus problem, pretty much the way I said I would in the previous post (set the textArea to uneditable, copy the character typed onto the textArea and I didn't even need to add the focus anywhere, things just seem to work). I then used a switch statement to work out what was pressed and act accordingly (if it's a space bar add a space, if it's any other button just do nothing except highlighting the corresponding virtual key button). Here is the relevant code:

import java.awt.Color;
public class TouchType extends JFrame{  
    private Color originalColour;//to …
Violet_82 89 Posting Whiz in Training

OK, thanks for the links I've had a look at those. Following that and what you said about focus, I run a little experiment with my application. I launched it, then typed on my keyboard and, as we know the text typed appeared inside the text area, but nothing happened to the keys on the virtual keyboard. Then I clicked on one of the keys on the virtual keyboard with my mouse and started to type again on my actual keyboard. Lo and behold, now the keys on the virtual keyboard change colour on key press and change it back on key release ( although for some strange reasons if I type too quickly they remain green, it's as if they don't have enough time to change back to the default colour) but there is no text appearing inside the textArea. I think I begin to understand this focus problem. So, one solution, as you hinted, is key binding. Looks a bit daunting thought I have to admit. The other solution, and please correct me if I'm wrong, is to:
1)disable the textArea so that you can't type in;
2)on keyPressed, get the character typed and copy it onto the textArea (although I have to find a way to make sure that when you press the spacebar you actually get a space rather than "space" and the same with the back button)
2)on keyPress make sure that the focus is on the button in the virtual keyboard, …

Violet_82 89 Posting Whiz in Training

Thanks for the explanation JamesCherrill. OK, so let's gloss over what I was trying to do before, clearly wrong. My understanding of the whole thing was this. Let's just forget about event handlings for just one second: when the GUI is displayed I can freely type in the textArea using my actual keyword, with no event handling occurring, as you would be able to type in a normal text field, so, I would have thought, I don't need to capture any typed event (so I left the method public void keyTyped{} empty), I'm only interested in keyPressed() and keyReleased(), correct?
I've made a few changes to the code, and added a variable to hold the button whose background needs to change, and an int variable to hold the key code: here is th code excerpt with the changes, but the colour isn't changing...

import java.awt.Color;
public class TouchType extends JFrame{  
    private Color originalColour;//to get the background of the original colour before changing it
    private int theChar;//to hold the vk constant
    private JButton buttonToHighlight;//button to hightlight

    ...
    public TouchType(){//constructor
        ...
        super("Typing application");
        KeyHandler handler = new KeyHandler();
        for(JButton currentButton:mp.values()){//going through all the buttons
            currentButton.addKeyListener(handler);//add listeners to buttons
            originalColour = currentButton.getBackground();//get the original colour of the button, don't need to do that here, just for testing
        }       
    }//end of constructor
    //private class for event handling
    private class KeyHandler implements KeyListener{
        public void keyPressed(KeyEvent event){
            theChar = event.getKeyCode();//get keyCode
            buttonToHighlight = mp.get(theChar);//get clicked button            
            buttonToHighlight.setBackground(Color.GREEN);//change button colour
        }
        public void keyReleased(KeyEvent event){ …
Violet_82 89 Posting Whiz in Training

Right, so unfortunately I'm having problems with getting constants out of key I press on the actual keyboard. I first used method getKeyCode(), which works but brings up the the keycode number, whereas I need to constants, the same I used in my map, si I soon realized that I needed getExtendedKeyCode(). The thing is that I can't get the latter to work, I get a symbol not found error, which is a bit worrying. So I went onto the net, onto the API trying to understand why that method doesn't work, and the only possible explanation is that maybe, since that method has been available since Java 7 (and I'm using java 7), somehow I'm not specifying I'm using java 7 or something weird like that. The method returns a int as does getKeyCode().
I tried different combinations, event.getExtendedKeyCode(), KeyEvent.getExtendedKeyCode() - admittedly not sure what the difference is between calling the method on event. or calling it on KeyEvent., but no joy
Relevant code below (I commented out the line using getKeyCode())

...
    public TouchType(){//constructor
        ...
        super("Typing application");
        KeyHandler handler = new KeyHandler();
        for(JButton currentButton:mp.values()){
            currentButton.addKeyListener(handler);
        }       
    }//end of constructor
    //private class for event handling
    private class KeyHandler implements KeyListener{
        public void keyPressed(KeyEvent event){
            //character = String.format("%s", event.getKeyCode());//get the constant            
            character = String.format("%s", event.getExtendedKeyCode());
            textArea.setText(character);
        }
        public void keyReleased(KeyEvent event){

        }
        public void keyTyped(KeyEvent event){

        }
    }
Violet_82 89 Posting Whiz in Training

OK no sorry, just me being a fool I don't need this functionality at all

character += String.format("%s", KeyEvent.getKeyText(event.getKeyCode()));
            textArea.setText(character);

because I'm typing inside the textArea so no need to copy character by character. Now I need to change the background color of the corresponding key on the virtual keyboard, will post when that's done, sorry, got a little confused

Violet_82 89 Posting Whiz in Training

Understood, thanks. It works now, at least the keys are displayed (although I will have to retweak the way the whole thing is displayed later on.)
On to event handling. I thought it would be nice to loop through the map and add a listener with a few lines of code, rather than doing it manually for all the buttons, but I'm not too sure that has worked (or that it is even acceptable. I had a look online and there were various way to do that, either with an iterator or with a for loop). Here I have coded in only one method to start with, haven't got to the other two as yet :

public TouchType(){//constructor
    ...
        KeyHandler handler = new KeyHandler();
        for(JButton currentButton:mp.values()){
        currentButton.addKeyListener(handler);
    }
}//end of constructor
//private class for event handling
    private class KeyHandler implements KeyListener{
        public void keyPressed(KeyEvent event){
            character = String.format("%s", KeyEvent.getKeyText(event.getKeyCode()));
            textArea.setText(character);
        }
        public void keyReleased(KeyEvent event){

        }
        public void keyTyped(KeyEvent event){

        }
    }

Is that allowed/good approach? When I press the button nothing gets added to the textArea, so I assume the listeners haven't been added

Violet_82 89 Posting Whiz in Training

er...pack() admittedly isn't there. Now that you mentioned that, I seem to remember having this conversation with you a few years back - before my gap with Java - just about the pack() and how important it was - can't remember why but I do remember you saying that, so I'll add it in on the test class (not attached to the thread), if I'm not mistaken that was the last thing to add after setVisible(true), something like this from memory:

/*TouchTypeTest.java*/
import javax.swing.JFrame;
public class TouchTypeTest{
    public static void main(String[] args){
        TouchType touchType = new TouchType();
        touchType.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        touchType.setSize(1900, 600);
        touchType.setVisible(true);
        touchType.pack();
    }
}

Now, about the layout of the keysPanel. I thought that keysPanel being just a panel could have had a BorderLayout so that it was easy to position it, it's currently positioned south in the JFrame, sorry for that. So, would then a GridLayout instead be better for keysPanel? Considering that there are 5 rows I could create another GridLayout of 1 row and 5 columns, but then how am I going to position the keysPanel inside the JFrame? If I just add it like soadd(keysPanel) where is it going to end up?
thanks

Violet_82 89 Posting Whiz in Training

Hi thanks, sorry for the slow reply but i've been trying to resolve a GUI rendering issue with this, in vain apparently, and I'm not sure I can move on before fixing it.
Basicallt, I don't seem to be able to properly display all the keys.
The JText area seems excessively big, and I don't seem to be able to change it even if I tweak the rows and columns values. I presume that the sheer size of the textArea is pushing down all the buttons, and when I say push down I mean get them to display outside the visible area? Is that possible?
Also, it seems like only the buttons in the last rows get added (I'm not even getting into the issue of the sizes of the button, I'll figure out how to resolve that later), and this is what I get:
keyboard_app.png

This is the situation, in peseudocode, that I believe I have:

JFrame                          //borderLayout
    JPanel labelPanel           //borderLayout NORTH
        JLabel                  //NORTH
        Jlabel                  //CENTER
    JTextArea                   //directly added to JFrame, CENTER
    JPanel keysPanel            //borderLayout SOUTH
        JPanel row1             //GridLayout            
            key 
            key 
            key 
        JPanel row2             //GridLayout            
            key 
            key 
            key 
        JPanel row3             //GridLayout            
            key 
            key 
            key 
        ...

And here is the updated code:

 /*TouchType.java*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JTextArea;
import javax.swing.JButton;
//import java.awt.FlowLayout;
import javax.swing.JLabel;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import static java.awt.event.KeyEvent.*;//needed for the key constants
import javax.swing.JScrollPane;
//for the map
import java.util.Map;
import java.util.HashMap;
import java.util.Set; …
Violet_82 89 Posting Whiz in Training

Ah OK, sorry I thought this was enough import java.awt.event.KeyEvent; but clearly it isn't importing the static ones.
OK, understood about the method, I'll amend.
After the amendments I'll go ahead and if it all compiles, I'll add the event handling (I know you said it shouldn't be done as last thing but I can't think any other way to go with this).
Now, a couple of questions I'm thinking about now: for the event handling I need to capture the KeyEvent constant generated by the key press - I'm referring to the actual keyboard - then save that in a variable, say clickedKeyVal or something, then iterate through the map looking for that clickedKeyValand if I find it change the background of the button that contains that value. Does it sound OK?
thanks

Violet_82 89 Posting Whiz in Training

Very good point JamesCherrill. I thought it would have been quicker to add it my way if that was possible, sorry.
OK, I think I'm slowly getting closer, but I must have done something silly as it's not compiling anymore and I'm getting errors due to the int constants I'm using. OK one step at a time.
First,I think I've implemented what you suggested, put loads of comments so that it should be easy to read as well, if there is any need to do so.
-I've added the method to create a button and insert it into the Map, but I created it with a void return as I didn't think I'd need it to return the button or anything for that matter, is that OK? Yours in the older post has a return type of JButton, I wasn't sure if mine had to do that too

private void createButton(int keyCode, String name){
        newButton = new JButton(name);
        mp.put(keyCode, newButton);
    }

and this is how I call it:

...
row5.add(createButton(VK_LEFT, "Left"));        
row5.add(createButton(VK_DOWN, "Bottom"));      
row5.add(createButton(VK_RIGHT, "Right"));
...

I've also created 5 JPanels for the rows with a GidLayout (5 different GridLayout objects) and added, as above, the buttons to the relevant
Here is the full code (I've found a mistake in the import KeyListener and KeyEvent, now amended

import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;




 /*TouchType.java*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JScrollPane;
//for the …
Violet_82 89 Posting Whiz in Training

thought you might disagree :-). You're making a valid point though, books do go out of date, but in my own experience (bear in mind that I'm not a programmer, and therefore I don't think like a programmer, not as yet at least and I do java as a hobby only for now and probably for some time before I get a good understading of things) it is important to get a gentle introduction to programming concepts etc and the book, or perhaps a book, even if it is an old one, helped an awful lot. Also, I presume, the core language isn't terribly different from year to year, even if there are surely new features, like lambda expressions to mention the only one I know. But obviously I'm not an expert, so that's just MHO :-). And combining the theory from the book plus the exercises and the support I get from the forum, provides altogether a good learning tool