How do I remove the border from multiple JButtons attached to one ActionListener (Created with for loop)?

I am creating a hangman game that uses a virtual keyboard for input. I created the keyboard layout using a for loop to create the buttons which then get put into a JButton ArrayList. All of the buttons make use of one ActionListener.

At the end of the game I need to reset all the buttons so they no longer have a border (A green or red border is placed around them during the game if the player guesses correctly). I have tried to loop through the JButton ArrayList to change the border but it only does it for the last button that was pressed. Is there a way that I can do this?

I also would like to know how to get the button back to it’s original design, as when I use button.setBorder(null) it makes the button basically disappear. I would like to remove the MatteBorder I set earlier in the program.

public void createKeyboard() {

    String buttonLabel;
    char buttonLabelChar;

    for (char c = 'A'; c <= 'Z'; c ++) {    
        buttonLabelChar = c;
        buttonLabel = "" + buttonLabelChar; 
        JButton button = new JButton(buttonLabel);

        keyboardArray = new ArrayList<JButton>();
        keyboardArray.add(button);

        button.setPreferredSize(new Dimension(40, 40));
        pnlKeyboard.add(button);
        button.addActionListener(
            new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {


                    hm.setLetterGuessed(event.getActionCommand().charAt(0));
                    hm.revealLetter();

                    if (hm.revealLetter()) {

                        button.setBorder(new MatteBorder(4, 4, 4, 4, Color.GREEN));
                        button.setEnabled(false);

                    }
                    else {

                        button.setBorder(new MatteBorder(4, 4, 4, 4, Color.RED));
                        button.setEnabled(false);
                        hm.loseLife();

                        setImage();
                    }

                    if (hm.winCheck()) {

                        JOptionPane.showMessageDialog(mainFrame, "You win!", "Game Over",
                                JOptionPane.INFORMATION_MESSAGE, new ImageIcon(Hangman.class.getResource("images/11rightleg.png")));

                        for (int i = 0; i < keyboardArray.size(); i ++) { // THIS DOESN'T WORK
                            button.setBorder(null);
                        }

                    }
                    else if (hm.getLives() == 0) {

                        JOptionPane.showMessageDialog(mainFrame, "You lose :(", "Game Over",
                                JOptionPane.INFORMATION_MESSAGE, new ImageIcon(Hangman.class.getResource("images/11rightleg.png")));

                    }


                    setWord();


                }
            }
        );

    }
}

Merge Sort Error when Merging Sub-Arrays Back Together

I get an ArrayIndexOutOfBounds error on line 157 because the index j is 10 when the largest index is 9. Any ideas what I need to change to keep merge sort working while fixing this error? This code is from my virtual school class but doesn’t seem to work.

package assignment;
import flvs.Movie;
import java.util.concurrent.ThreadLocalRandom;

public class MovieClient3
{
static void traverseMovies(Movie[] movies)
{
    for(flvs.Movie m : movies)
    {
        System.out.printf("Title: %s, Year: %d, Studio: %s%n", m.getTitle(), m.getYear(), m.getStudio());
    }
}

public static void main(String[] args)
{
    Movie[] movies = new Movie[]
    {
        new Movie("ABC", 2005, "Studio 03"),
        new Movie("DEF", 2006, "Studio 02"),
        new Movie("GHI", 2001, "Studio 01"),
        new Movie("JKL", 2003, "Studio 04"),
        new Movie("MNO", 2002, "Studio 05"),
        new Movie("PQR", 2007, "Studio 06"),
        new Movie("ST", 2010, "Studio 07"),
        new Movie("UV", 2009, "Studio 08"),
        new Movie("WX", 2008, "Studio 10"),
        new Movie("YZ", 2007, "Studio 09")
    };

    jumbleArray(movies);
    System.out.println("Jumbling array...");
    Movie[] jumbled = movies.clone();
    System.out.println("Jumbled array:");
    traverseMovies(movies);

    MergeSortByTitle(movies, 0, movies.length);
    System.out.println();
    System.out.println("Sorted array using title:");
    traverseMovies(movies);
    /*
    System.out.println();
    System.out.println("Jumbling array again...");
    movies = jumbled;

    mergeSortByTitle(movies, 2);
    System.out.println();
    System.out.println("Sorted array using title (inverted):");
    traverseMovies(movies);

    System.out.println();
    System.out.println("Jumbling array again...");
    movies = jumbled;

    mergeSortByYear(movies, 1);
    System.out.println();
    System.out.println("Sorted array using year:");
    traverseMovies(movies);

    System.out.println();
    System.out.println("Jumbling array again...");
    movies = jumbled;

    mergeSortByYear(movies, 2);
    System.out.println();
    System.out.println("Sorted array using year (inverted):");
    traverseMovies(movies);

    System.out.println();
    System.out.println("Jumbling array again...");
    movies = jumbled;

    mergeSortByStudio(movies, 1);
    System.out.println();
    System.out.println("Sorted array using studio:");
    traverseMovies(movies);

    System.out.println();
    System.out.println("Jumbling array again...");
    movies = jumbled;

    mergeSortByStudio(movies, 2);
    System.out.println();
    System.out.println("Sorted array using studio (inverted):");
    traverseMovies(movies);*/

}

static void jumbleArray(Object[] array)
{
    int index;
    Object temp;
    ThreadLocalRandom random = ThreadLocalRandom.current();
    for (int i = 0; i < array.length - 1; i++)
    {
        index = random.nextInt(i + 1);
        temp = array[index];
        array[index] = array[i];
        array[i] = temp;
    }
}

static boolean compare(Movie a, Movie b, String mode)
{
    if(mode.equals("title"))
        return a.getTitle().compareTo(b.getTitle()) >= 0;
    else
        return true;
}

static void MergeSortByTitle(Movie[] array, int left, int right)
{
    if(left == right) return;

    int mid = (left + right)/2;

    MergeSortByTitle(array, left, mid); 
    MergeSortByTitle(array, mid + 1, right);

    merge(array, left, mid, right, "title");
}

//  Left run is A[iLeft :iRight-1].
// Right run is A[iRight:iEnd-1  ].
static void merge(Movie[] array, int left, int mid, int right, String mode)
{
    Movie[] temp = new Movie[right - left + 1];

    int i = left;
    int j = mid + 1;
    int n = 0;

    while(i <= mid || j <= right) // put elements (sorted) into temp
    {
        System.out.println("i: " + i + "    j: " + j + "    left: " + left + "   right: " + right);
        if(i > mid) //we have emptied the left half, insert the right half
        { 
            temp[n] = array[j]; 
            j++;
        }
        else if(j > right) //we have emptied the right half, insert the left half
        {
            temp[n] = array[i]; 
            i++;
        }
        else if(compare(array[i], array[j], "title"))
        {
            // both sections have values so we compare and see if
            // smallest is in i position − if so, pull from there
            temp[n] = array[i]; 
            i++;
        }
        else
        {
            // smallest is in j position − pull from there
            temp[n] = array[j]; 
            j++;
            } 
            n++;
        }
        // put elements back into a in a[left] to a[right] 
        for(int k = left; k <= right; k++) 
            array[k] = temp[k - left];
}

static void mergeSortByYear(Movie[] array, int left, int right)
{

}

static void mergeSortByStudio(Movie[] array, int left, int right)
{

}

}

dummy text at the bottom because stackoverflow makes me add superfluous text that doesnt need to be here filler filler

Java – Printing commas in a loop

I’m running into this problem where if want to loop through an array and print out its contents separated by a comma, it prints out an extra at the end.
I did some searching but, couldn’t find an answer that worked for this situation.

Code:

public String toString(){

    String hold= "";
    for(int i = 0; i < array.length; i ++){

        if(array[i] == true){
            hold + = i;
            if(i != array.length-1)
                hold+= ",";
        }
    }
    return hold;
}

nullpointer exception in array list

public String tornadoComing()
{
    int open= 0;
    int closed= 0;
    for (int i= 0; i< doorsHave.length; i++)
    {
        doorsHave[i].open();
    }
    for (int i=0; i<doorsNeed.size();i++)
    {
        if (doorsNeed.get(i).getState()== false)
        {
            doorsNeed.remove(doorsNeed.get(i));
            closed++;
        }
        else 
        {
            open++;
        }
    }
    return open + " doors opened and " + closed + " doors closed";
} 

I am uncertain why this is throwing a null pointer.

How to correctly upload a video to server using okhttp client

I am trying to upload a video to a server using okhttp client and although the onsuccess method is reached the video is not playable on the website.
My question is, am I uploading the video correctly using the storage path or am I missing something?

public void videoUploadTo(String url, String storageUrl) {
    OkHttpClient client = new OkHttpClient();
    File videoFile = new File(storageUrl);
    Uri videoUri = Uri.fromFile(videoFile);

    String content_type = getMimeType(videoFile.getPath());
    RequestBody fileBody = RequestBody.create(MediaType.parse(content_type), videoFile);

    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("type", content_type)
            .addFormDataPart("uploaded_video", storageUrl.substring(storageUrl.lastIndexOf("/") + 1), fileBody)
            .build();

    Request request = new Request.Builder()
            .url(siteUrl + url)
            .put(requestBody)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.d("onfailure video", e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d("onResponse video", response.message());
        }
    });
}

Project Jigsaw vs Maven

From Jigsaw Project:

Make it easier for developers to construct and maintain libraries and
large applications, for both the Java SE and EE Platforms.

I’m trying to learn what project Jigsaw is and till now it seems that the goal of Project Jigsaw somewhere overlap with what we did using Maven (or Gradle): dependency management.

  • Is it a threat to build tools like Maven?
  • Or my understanding is wrong and project Jigsaw going to complement these build tools in some way?

How to test IOException for a JSONObject?

I have the code below:

public static void writeJson(JSONObject outputFinal) throws IOException {
    fw.write(outputFinal.toString(3));
    fw.flush();
    fw.close();
}

I am trying to write a JUnit test to test the IOException.
How can I make the JSONObject passed as a param trigger an exception?

Provisioning TLS/SSL certificates, session/master keys

We need a simple yet secure mechanism to provision server and client certs to clients based on a simple password for a non-web application.

We do NOT want to deal with (dubious) CA’s installing certificates etc. The clients start completely empty, no root certificates.

The best way is to use Secure Remote Password (SRP). But nobody implements that so no good.

A classic way is to hash nonces with the password. Unlike SRP requires a very strong password to defeat off line attacks, but we can insist on that.

But then we have the man-in-the middle problem. One way to avoid that is to use some aspect of the (unverified) TLS protocol as part of the nonce. This could be the Session Key, the Pre Master, or maybe Session Id.

Has anybody had any experience with this sort of thing? And what TLS ephemeral keys are easy to get at from OpenSSL, Java, .Net etc.?

(We can open a TLS session without any certs and be sure we are securely talking to someone, then we just need to verify who that someone is.)

Once we have established a secure channel, we can send certs and keys across it and proceed in the normal way. It is the provisioning that is the hard part.

(One extra twist is that in our environment for bad reasons the server needs to create the client private key and send it to the client.)

(BTW Anyone that thinks that TLS is secure should read up on Phishing and broken CAs. It is no good to blame the user for not knowing the fairly complex rules for checking URLs (its the bit in the middle that counts, before the third “/”…). We all know it is broken, and how to fix it, but there is no money to be made in fixing it.)

Remove line from jTextArea

I have a jtextarea that is filled with numbers with no duplicates.There is an add and remove button. I have programmed the add button, but I am struggling with programming the remove button. I know how to remove the number from the array, but I’m not sure how to remove the number from the jtextarea.

How do I remove a line from a jtextarea that contains a certain number?

Extra notes:
The only input is integers.

Why do we need a specific search for unreachable objects in Old Generation if we know all dead objects after marking them on the Young Generation?

I know that in CMS and G1 heap is divided into Eden, Survivor spaces and Old Generation with only difference that in CMS this division is real (these spaces are contagious and located in different parts of memory) and in G1 it is logical (the heap is split into ±2000 dynamic regions from 1 to 32 MB each).

In both cases when Eden space is fulfilled threshold Young evacuation starts and the steps are following:
Initial marking.
STW. Mark the roots of the application.
Concurrent marking.
From the roots of the links there are transitions to objects from these objects to other objects and thus the achieved objects are marked alive.
Remark.
STW. Objects created during concurrent marking are also marked live (floating garbage).
Cleanup
This final phase prepares the ground for the upcoming evacuation phase, counting all the live objects in the heap regions, and sorting these regions by expected GC efficiency.

If the fulfillment of heap reaches the threshold then mixed evacuation (Young + Old) starts in G1.
Founding dead objects in Old Generation is based on ‘Remembered Sets’. Each region has a remembered set that lists the references pointing to this region from the outside. These references are regarded as additional GC roots.

After G1 makes a decision which regions from old and young generations to add to collection set.

Why do we need remembered sets and specific search for unreachable objects in Old Generation if we have the entire graph of all objects and know all alive and dead objects after marking them on the Young evacuation level?