Search code examples
javaarraysswinguser-interfacejlabel

GUI representation of arrays in java


I'm kinda new to java and I'm making an applet where I need to display an array (numbers from 0 to 255) like the ones in this applet (I am putting it inside a JScrollPane):

RC4 Cipher Applet

I also want to deal with each entry and the value inside it later. I tried using JTable but the maximum number of columns is 100. I thought about a JLabel for each entry but it would take forever..

Excuse me if this is a repeated question but I searched the questions here I couldn't find what I need

Oh and no this is not a homework I'm just working on a little project for myself :) Thanks!


Solution

  • Well, using JLabels wouldn't take forever if you do something like this:

    for (int i = 0; i < array.length; i++) {
        contentPanel.add(new JLabel(array[i]));
    }
    

    That's the first approach. You could also draw a grid with the numbers yourself by subclassing JPanel and overriding paintComponent(Graphics). Example:

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int currX = 10, currY = 10; // A 10px offset
        int gridBoxSize = 50; // In pixels. Should be large enough for three digits.
    
        for (int i = 0; i < array.length; i++) {
            if (currX + gridBoxSize > this.getWidth()) {
                currX = 10;
                currY += gridBoxSize;
            }
            g.setColor(Color.BLACK);
            g.drawRect(currX, currY, gridBoxSize, gridBoxSize);
            g.drawString(new String(array[i]), currX + 2, currY + 2);
        }
    }
    

    Note:

    • I assumed the array you are talking about in your question is declared like this: int[] array;;
    • The above code is only a quick draft, I didn't compile or test it.