How to create a JLabels array in Java for printing in JFrame

I am trying to create an array of tags. Each label has a different value that exits the function. I do not know the exact number of tags to be used. I mean, any number of values ​​can be printed. Please help me do this.

+4
source share
4 answers

Just just one method returns an array or some collection of JLabels and add all of them to your JComponent (e.g. JPanel)

class MyPanel extends JPanel{ public MyPanel(){ super(); showGUI(); } private JLabel[] createLabels(){ JLabel[] labels=new JLabel[10] for (int i=0;i<10;i++){ labels[i]=new JLabel("message" + i); } return labels; } private void showGUI(){ JLabel[] labels=createLabels(); for (int i=0;i<labels.length();i++){ this.add(labels[i]); } } } 
+7
source

If possible, do not use separate JLabel , but JList , which will take care of the layout and scrolling if necessary.

Java Tutorial - How to list us :

alt text
(source: sun.com )

+2
source

Are you kiddin? Well, if you're serious, first take a look at some of the Java APIs, such as JLabel, JPanel, and some language elements.

Then you can do something like (I'm sure my code will not compile)

 public static JPanel getLabels(int count) { JPanel panel = new JPanel(new FlowLayout()); for(int i =0; i<count; i++) { panel.add(new JLabel(theFunctionThatCannotBeNamedHere(i))); } return panel; } 

Please note that theFunctionThatCannotBeNamedHere is the function you were talking about.

0
source

In fact, you can create an array of any Swing component, since each Swing component is basically a composite data type. Try the following:

 javax.swing.JTextField[] array = new javax.swing.JTextField[number_of_elements]; 
0
source

Source: https://habr.com/ru/post/1308006/


All Articles