Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-4041-

Java array help

Name: Anonymous 2010-07-30 21:13

hey /prog/ just wondering if anyone could give me a hand with some java code. Basically I am trying to place labels from an array of JLabels into a JPanel using .add, but it doesn't want to work. I have never used an array of JLabels before, so i am certain that i fucked up somewhere.

Code:

public void setProp() {

        for (int i = 0; i < label.length; i++) {
            label[i] = new JLabel("");
            label[i].setPreferredSize(labelDim);
            label[i].setIcon(new ImageIcon(this.getClass().getResource("blank.gif")));
            label[i].setEnabled(true);
            label[i].setVisible(false);
            pnlMap.add(label[i]);

        }
    }


also blank.gif is just a black square and the dimensions are set to match the icon dimensions.

any input would be appreciated

Name: Anonymous 2010-07-30 21:20

label[i].setVisible(false);
Great work, Sparky.

Name: Anonymous 2010-07-30 21:51

yeah i know, thats not the problem, im getting an IllegalArguementException for adding the labels to the panel

Name: Anonymous 2010-07-30 22:03

>>3
Good thing you mentioned that in your opening post then, twit.
Try reading the fucking documentation.

Name: Anonymous 2010-07-30 22:15

Works on my machine!

Name: Anonymous 2010-07-30 22:15

>>1
I think you're passing an illegal argument when adding the labels to the panel.

Name: Anonymous 2010-07-30 22:16

>>4
sorry for wasting your very valuable time by adding on a small tidbit of information a post later.

Name: Anonymous 2010-07-30 22:18

>>6
Yeah thats what the exception implies, but that method accepts a Component as an arguement, are JLabels not considered Components? or just not in that context?

Name: Anonymous 2010-07-30 22:24

>>3
You're probably getting the IllegalArgumentException from the method addImpl(Component comp, Object constraints, int index) for which add(Component comp) is a convenience method.  Read your Javadocs about that.

Without knowing more about what you did to pnlMap, all you can do to help is post the whole class this method is in, and the the stack trace (error message).

Just as a suggestion, also use setSize(Dimension) method along with setPreferredSize(Dimension).

Name: Anonymous 2010-07-30 22:34

>>9
Alright ill take a look

Stack:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException
        at org.netbeans.lib.awtextra.AbsoluteLayout.addLayoutComponent(Unknown Source)
        at java.awt.Container.addImpl(Container.java:1074)
        at java.awt.Container.add(Container.java:365)
        at Test.setProp(Test.java:40)
        at Test.bntTileActionPerformed(Test.java:171)
        at Test.access$000(Test.java:22)
        at Test$1.actionPerformed(Test.java:140)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
        at java.awt.Component.processMouseEvent(Component.java:6263)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
        at java.awt.Component.processEvent(Component.java:6028)
        at java.awt.Container.processEvent(Container.java:2041)
        at java.awt.Component.dispatchEventImpl(Component.java:4630)
        at java.awt.Container.dispatchEventImpl(Container.java:2099)
        at java.awt.Component.dispatchEvent(Component.java:4460)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
        at java.awt.Container.dispatchEventImpl(Container.java:2085)
        at java.awt.Window.dispatchEventImpl(Window.java:2478)
        at java.awt.Component.dispatchEvent(Component.java:4460)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)


The pnlMap is just default except for AbsoluteLayout

Name: Anonymous 2010-07-30 22:55

>>10
Did you setBounds(x, y, width, height)? No, you didn't.

Name: Anonymous 2010-07-30 23:05

>>11
setBounds for the labels?

Name: Anonymous 2010-07-30 23:17

>>10
The pnlMap is just default except for AbsoluteLayout
And I'm sure you're in an excellent position to judge what code is and isn't affecting your problem, since you couldn't actually figure it out yourself. Just post the fucking code.

Why does getting idiots like you to actually let us help when you come to us for that help always have to be like pulling teeth?

Name: Anonymous 2010-07-30 23:32

>>11
Not setting his component positions was his most obvious omission but I wasn't going to spoonfeed it to him.

The pnlMap is just default except for AbsoluteLayout
You may say that but your stack trace says that is where your program kicks the bucket.

Name: Anonymous 2010-07-30 23:45

Go bug StackOverflow.

Name: Anonymous 2010-07-30 23:47

>>13
Because they want to make it seem like they actually know what they're doing, except for this weird corner case (hideously obfuscated in the docs, you see) of adding a label to a panel.

Name: Anonymous 2010-07-31 0:00

>>13
>>14
>>16
Know what guys? this is the first time I have ever tried something like this, and all I have ever done was retarded input/output school work that was not complex at all (which i am sure this isnt either but i am retarded).

I have never been to /prog/ before (as i am sure you all have noticed), so maybe toss me a rope.

as far as code goes, that method is basically it. I have a button that calls the method, and said button and panel were made by dragging them onto my frame in netbeans.

and i know this is a long enough explanation, but i just want a push in the right direction so i can hopefully get this figured out.

tl;dr: im retarded, just looking for some help

Name: Anonymous 2010-07-31 0:04

>>17
Did you setBounds?

Name: Anonymous 2010-07-31 0:09

>>18
I have yet to do that because no one clarified what objects bounds i was setting, is it the labels?

Name: Anonymous 2010-07-31 0:13

>>17
so maybe toss me a rope.
Promise to hang yourself?
Reading other people's posts and actually doing what they fucking ask you when you're trying to get them to help you isn't something that's unique to /prog/. I know for a fact that it is, in fact, quite a standard thing to have.

Post your fucking code or get the fuck out.

Name: Anonymous 2010-07-31 0:17

>>19
Look it up.

Name: Anonymous 2010-07-31 0:18

>>17
There was a time when people new to a board would lurk for a bit to get a feel for the culture, instead of just immediately shitting it up with worthless threads.

Name: Anonymous 2010-07-31 0:19

>>20


import java.awt.Dimension;
import java.io.*;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Test extends javax.swing.JFrame {
    //initializes arrays for map

    ImageIcon tiles[] = new ImageIcon[144];
    JLabel labels[] = new JLabel[144];
    JLabel label[] = new JLabel [4];
    int numArray[] = new int[144];
    //dimension object for setting label array properties
    Dimension labelDim = new Dimension(46, 27);

    public void setProp() {

        for (int i = 0; i < label.length; i++) {
            label[i] = new JLabel("");
            label[i].setPreferredSize(labelDim);
            label[i].setIcon(new ImageIcon(this.getClass().getResource("blank.gif")));
            label[i].setEnabled(true);
            label[i].setVisible(false);
            pnlMap.add(label[i]);

        }
    }
    //fix this shit
   public void placeTiles() {
        int x = 0;
        int y = 0;
        int k = 0;
            for (int row = 0; row < 12;) {
                for (int col = 0; col < 12; col++) {
                    if (row == 0) {
                        if (col == 0){
                        labels[col].setLocation(20, 20);
                        x = labels[col].getX();
                        y = labels[col].getY();
                        }

                    } else {
                     labels[col].setLocation(x-(k*22), (y+(col*13)));
                    }
                    if (col==11){
                        col = 12;
                        row++;
                        k++;
                    }
                }

            }

    }

    //This method translates integer values from the num array into
    //tile images in the image array
    public void defineTiles() {
        //for loop to go through entire num array
        for (int a = 0; a < 144; a++) {
            //places value from index of num array in temp variable
            int temp = numArray[a];
            //sets proper tile in corresponding index of image array
            switch (temp) {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
            }
        }
    }

    public void openText() {
        String row;
        try {
            //initiated reader for text file
            BufferedReader fileRead = new BufferedReader(new FileReader("test.txt"));
            //because maps are saved in 1 line, just reads line into string
            row = fileRead.readLine();
            //loop to translate line into numerical values in array for each tile
            for (int b = 0; b < 144; b++) {
                //splits string into characters and then convertst to an integer
                char character = row.charAt(b);
                String string = Character.toString(character);
                numArray[b] = Integer.parseInt(string);
            }
            //closes stream
            fileRead.close();
            //catches exception
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex);
        }
    }

    /** Creates new form Test */
    public Test() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        bntTile = new javax.swing.JButton();
        lblSprite = new javax.swing.JLabel();
        lbl1 = new javax.swing.JLabel();
        lbl2 = new javax.swing.JLabel();
        lbl3 = new javax.swing.JLabel();
        pnlMap = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(500, 500));
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        bntTile.setText("tile");
        bntTile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntTileActionPerformed(evt);
            }
        });
        getContentPane().add(bntTile, new org.netbeans.lib.awtextra.AbsoluteConstraints(306, 32, -1, -1));

        lblSprite.setIcon(new javax.swing.ImageIcon(getClass().getResource("/knight.gif"))); // NOI18N
        getContentPane().add(lblSprite, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 40, 20, 30));

        lbl1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/0.gif"))); // NOI18N
        getContentPane().add(lbl1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 50, -1, 30));

        lbl2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/0.gif"))); // NOI18N
        getContentPane().add(lbl2, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 80, -1, 30));

        lbl3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/0.gif"))); // NOI18N
        getContentPane().add(lbl3, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 120, -1, 30));

        pnlMap.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pnlMap.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        getContentPane().add(pnlMap, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 140, 380, 360));

        pack();
    }// </editor-fold>                       

    private void bntTileActionPerformed(java.awt.event.ActionEvent evt) {                                       
        int x = lbl1.getX();
        int y = lbl1.getY();
        lbl2.setLocation((x - 22), (y + 13));
        lbl3.setLocation((x + 22), (y + 13));
        lblSprite.setLocation(((lbl2.getX()) + 10), ((lbl2.getY()) - 10));
        openText();
        setProp();
        //placeTiles();
    }                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Test().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                    
    private javax.swing.JButton bntTile;
    private javax.swing.JLabel lbl1;
    private javax.swing.JLabel lbl2;
    private javax.swing.JLabel lbl3;
    private javax.swing.JLabel lblSprite;
    private javax.swing.JPanel pnlMap;
    // End of variables declaration                  
}


There is a lot of shit there that isn't really related, but you asked for code

Name: Anonymous 2010-07-31 0:25

>>23
[code] tags, for fuck's sake.
And why the hell are you using a drag-and-drop GUI builder when you don't even know the basics of the library you're using?

I swear, 90% of the problems nubs at Java schools run into when ``programming'' are down to their bullshit IDEs.

Name: Anonymous 2010-07-31 0:27

>>24

sorry, that should have been a no brainer, still used to imageboard posting. And i think that i mentioned how high my level of retardation is when it comes to this problem, so im just working with what i know

Name: Anonymous 2010-07-31 2:03

Don't help him.

Name: Anonymous 2010-07-31 3:02

>>23
Okay, start with the very basic: do what people are suggesting and setBounds(int x, int y, int width, int height) on each JLabel object as you create it.

Also, and this is a big also, add a finally in method openText to make sure the BufferedReader gets closed.
public void openText()
{
   String row = "";
   BufferedReader fileRead = null;
   try
   {
      fileRead = new BufferedReader(new FileReader("test.txt"));
      row = fileRead.readLine();
      for(int b = 0; b < 144; b++)
      {
         String string = row.substring(b, b+1);
         numArray[b] = Integer.parseInt(string);
      }
   }
   catch(Exception ex)
   {
      JOptionPane.showMessageDialog(null, ex);
   }
   finally
   {
      try
      {
         if(fileRead != null) fileRead.close();
      }
      catch(Exception e) { }
      fileRead = null;
   }
}

It's just good practice to make sure your streams get to close properly after you're done with them, no matter how temporary they are.

Name: Anonymous 2010-07-31 4:44

Java thread with serious posts.
Nipaaaaaaaaaaaaa~.

Name: Anonymous 2010-07-31 5:27

Why don't you download your libraries' sources, set some breakpoints and get the fuck out?

Name: Anonymous 2010-07-31 9:13

Haha, "netbeans".

Name: Anonymous 2010-07-31 10:26

>>27
alright, i will do that and see where i can go from there. Thank you very much for your help

>>29
 This too.

So, thanks to everyone in this thread, ill try everything that you suggested and see where that leaves me. I know you are eager to get rid of me, so ill gtfo now, and just let this thread die

Name: Anonymous 2010-07-31 10:29

ill try
How unhealthy.

Name: Anonymous 2010-07-31 10:59

This thread is everything that we fought against. sage.

Name: Anonymous 2010-07-31 11:02

>>33
Only as of >>33 it is.

Name: Anonymous 2010-07-31 12:16

>>33
sage is not a weapon. It is a standard.

Name: Anonymous 2010-07-31 12:24

>>35
Or a herb. Like Patchouli.

Name: Anonymous 2010-07-31 12:32

>>36
*Patchouli Knowledge

Name: Anonymous 2010-07-31 13:41

>>37
*Sage knowledge

Name: Anonymous 2010-07-31 13:50


import java.awt.*;
import java.io.*;
import javax.swing.*;

public class Test extends javax.swing.JFrame {
    //initializes arrays for map

    ImageIcon tiles[] = new ImageIcon[144];
    JLabel labels[] = new JLabel[144];
    JLabel label[] = new JLabel [4];
    int numArray[] = new int[144];
    //dimension object for setting label array properties
    Dimension labelDim = new Dimension(46, 27);

    public void setProp() {

        for (int i = 0; i < label.length; i++) {
            label[i] = new JLabel("");
            label[i].setPreferredSize(labelDim);
            label[i].setIcon(new ImageIcon(this.getClass().getResource("blank.gif")));
            label[i].setEnabled(true);
            label[i].setVisible(false);
            pnlMap.add(label[i]);

        }
    }
    //fix this shit
   public void placeTiles() {
        int x = 0;
        int y = 0;
        int k = 0;
            for (int row = 0; row < 12;) {
                for (int col = 0; col < 12; col++) {
                    if (row == 0) {
                        if (col == 0){
                        labels[col].setLocation(20, 20);
                        x = labels[col].getX();
                        y = labels[col].getY();
                        }

                    } else {
                     labels[col].setLocation(x-(k*22), (y+(col*13)));
                    }
                    if (col==11){
                        col = 12;
                        row++;
                        k++;
                    }
                }

            }

    }

    //This method translates integer values from the num array into
    //tile images in the image array
    public void defineTiles() {
        //for loop to go through entire num array
        for (int a = 0; a < 144; a++) {
            //places value from index of num array in temp variable
            int temp = numArray[a];
            //sets proper tile in corresponding index of image array
            switch (temp) {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
            }
        }
    }

    public void openText() {
        String row;
        try {
            //initiated reader for text file
            BufferedReader fileRead = new BufferedReader(new FileReader("test.txt"));
            //because maps are saved in 1 line, just reads line into string
            row = fileRead.readLine();
            //loop to translate line into numerical values in array for each tile
            for (int b = 0; b < 144; b++) {
                //splits string into characters and then convertst to an integer
                char character = row.charAt(b);
                String string = Character.toString(character);
                numArray[b] = Integer.parseInt(string);
            }
            //closes stream
            fileRead.close();
            //catches exception
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex);
        }
    }

    /** Creates new form Test */
    public Test() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        bntTile = new javax.swing.JButton();
        lblSprite = new javax.swing.JLabel();
        lbl1 = new javax.swing.JLabel();
        lbl2 = new javax.swing.JLabel();
        lbl3 = new javax.swing.JLabel();
        pnlMap = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(500, 500));
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        bntTile.setText("tile");
        bntTile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntTileActionPerformed(evt);
            }
        });
        getContentPane().add(bntTile, new org.netbeans.lib.awtextra.AbsoluteConstraints(306, 32, -1, -1));

        lblSprite.setIcon(new javax.swing.ImageIcon(getClass().getResource("/knight.gif"))); // NOI18N
        getContentPane().add(lblSprite, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 40, 20, 30));

        lbl1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/0.gif"))); // NOI18N
        getContentPane().add(lbl1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 50, -1, 30));

        lbl2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/0.gif"))); // NOI18N
        getContentPane().add(lbl2, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 80, -1, 30));

        lbl3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/0.gif"))); // NOI18N
        getContentPane().add(lbl3, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 120, -1, 30));

        pnlMap.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pnlMap.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        getContentPane().add(pnlMap, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 140, 380, 360));

        pack();
    }// </editor-fold>                       

    private void bntTileActionPerformed(java.awt.event.ActionEvent evt) {                                       
        int x = lbl1.getX();
        int y = lbl1.getY();
        lbl2.setLocation((x - 22), (y + 13));
        lbl3.setLocation((x + 22), (y + 13));
        lblSprite.setLocation(((lbl2.getX()) + 10), ((lbl2.getY()) - 10));
        openText();
        setProp();
        //placeTiles();
    }                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Test().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                    
    private javax.swing.JButton bntTile;
    private javax.swing.JLabel lbl1;
    private javax.swing.JLabel lbl2;
    private javax.swing.JLabel lbl3;
    private javax.swing.JLabel lblSprite;
    private javax.swing.JPanel pnlMap;
    // End of variables declaration                  
}

Name: wtf? 2010-08-01 5:53

<code class="prettyprint"><span class="pln">sage</span></code>

Name: Anonymous 2010-08-01 10:18

>>36
a herb
IHBT

Name: Anonymous 2010-08-01 14:21

>>41
Pardon, what? I'm afraid I didn't quite catch that, as I was too occupied being British.

Name: Anonymous 2010-08-01 14:52

>>41
an 'erb

Name: Anonymous 2010-08-01 15:16

Herb Sutter.

Don't change these.
Name: Email:
Entire Thread Thread List