1

I have a code that automatically create jlabels .

I want that each label should be at a row, Not beside!

I use this code:

            lbl = new JLabel[rows];
        for (int i = 0; i < rows; i++) {
            lbl[i] = new JLabel(arrayResultRow[i].toString()+ "\n" );
        }

But \n does not work!

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Sajad
  • 2,273
  • 11
  • 49
  • 92

1 Answers1

3

Google and study the Java Swing layout manager tutorial and start reading.

Likely you're adding the JLabels to a JPanel which uses FlowLayout by default, and you need to change the layout of the container to GridLayout or BoxLayout.

Edit: here's the link: Laying out Components.

i.e.,

// add JLabels to a JPanel that uses GridLayout set to have
// 1 column and "rows" number of rows.
JPanel labelHolder = new JPanel(new GridLayout(rows, 1);
lbl = new JLabel[rows];
for (int i = 0; i < rows; i++) {
  lbl[i] = new JLabel(arrayResultRow[i].toString());
  labelHolder.add(lbl[i]);
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • My whole class is this: http://stackoverflow.com/questions/17595816/show-jlabel-on-jbutton-click – Sajad Jul 17 '13 at 21:35
  • @Sajjad-: Yep, you're using FlowLayout. Don't. I think I recognize your code style as you are writing methods that have side effects on fields, something that should be avoided. You were doing this in code posted in previous questions here. – Hovercraft Full Of Eels Jul 17 '13 at 21:39
  • Yes, Works so nice! Thanks! – Sajad Jul 17 '13 at 21:43
  • I want to show `mysql` database data into a `jtable` and now, i am trying to do this, Can you show me an example of this job? – Sajad Jul 17 '13 at 21:52
  • @Sajjad- An example of what? A JTable? For my money, I'd Google the JTable tutorial and start there. – Hovercraft Full Of Eels Jul 17 '13 at 21:59
  • No, for loading data into jtabel. – Sajad Jul 17 '13 at 22:06
  • For setup table model with database data – Sajad Jul 17 '13 at 22:07
  • @Sajjad- learning to do this will take studying on how to use JTables and TableModels. You can find a lot on this subject by searching this site. Also have a look at Rob Camick's [Java Tips Weblog](http://tips4java.wordpress.com/) especially the section on [Table from Database](http://tips4java.wordpress.com/2009/03/12/table-from-database/). So rather than ask us to provide you with a sample, you will want to study the samples that are already available for you to review. You just have to put in the effort to find them. – Hovercraft Full Of Eels Jul 17 '13 at 22:11
  • Please see this: http://stackoverflow.com/questions/18177249/initialize-variable-with-constructor – Sajad Aug 12 '13 at 21:38