2

Hi i am trying to make java desktop application where i am using multiple jlabel i want to give little spaces between every label

how can i achieve this

here is my code

public class Second extends javax.swing.JFrame {
JLabel label=new JLabel();
    /**
     * Creates new form Second
     */
    public Second() {
          this.getContentPane().setBackground(new java.awt.Color(255, 140, 0));
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setUndecorated(true);
JButton print= new JButton();
print.setBackground(new java.awt.Color(153, 153, 0));
            print.setOpaque(true);
            print.setBounds(525,1282,130,85);
            print.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
          print.setForeground(new java.awt.Color(255,255,255));
            print.setText("Print");
            this.add(print);

          JButton home= new JButton();
home.setBackground(new java.awt.Color(153, 153, 0));
            home.setOpaque(true);
            home.setBounds(640,1282,130,85);
            home.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
          home.setForeground(new java.awt.Color(255, 255,255 ));
            home.setText("Home");
            this.add(home);

int Height = 134;
int a=100;
             ArrayList<JLabel> label = new ArrayList<JLabel>();

  for(int i=0;i<23;i++){
         JLabel j = new JLabel();
           j.setBackground(new java.awt.Color(255, 140, 255));
            j.setOpaque(true);
            j.setBounds(5,Height,378,50);
            j.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
          j.setForeground(new java.awt.Color(128, 128, 128));
            j.setText("Case                                  Item                         CourtNo   ");
             LineBorder line = new LineBorder(Color.blue, 2, true);

       j.setBorder(line);
            this.add(j);
            label.add(j);


               JLabel j1 = new JLabel();
            j1.setBackground(new java.awt.Color(255, 140, 0));
            j1.setOpaque(true);
            j1.setBounds(390,Height,768,50);
            j1.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
            j1.setForeground(new java.awt.Color(128, 128, 128));
            j1.setText("Case                                 Item                         CourtNo   ");
            this.add(j1);
            label.add(j1);


               Height = Height +50;
               a=a+10;
  }




        initComponents();


    }
  public void paint(Graphics g) {
        super.paint(g);

         Graphics2D g3 = (Graphics2D) g;
      BasicStroke bs = new BasicStroke(2);
    Line2D lin1 = new Line2D.Float(386, 100, 386, 1282);
      Line2D lin = new Line2D.Float(0, 1283, 768, 1283);
      Line2D line3=new Line2D.Float(400,1284,400,1364);
    g3.setStroke(bs);
     g3.setColor(Color.white);
     g3.draw(lin1);
     g3.draw(lin);
     g3.draw(line3);;

  }
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Second().setVisible(true);
            }
        });
    }}

My new code

public class Testing1 extends javax.swing.JFrame {


    public Testing1() {

             JFrame frame = new JFrame();
        JPanel panel = createPanel();
        panel.setLocation(100, 100);
        //panel.setLayout(null);
        this.add(panel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);

        initComponents();
    }


     private JPanel createPanel() {
    jPanel1 = new JPanel(new GridLayout(0, 1, 10, 5));
        EmptyBorder panelBorder = new EmptyBorder(10, 10, 10, 10);
        jPanel1.setBorder(panelBorder);
        EmptyBorder border = new EmptyBorder(5, 20, 5, 20);
        LineBorder line = new LineBorder(Color.blue, 2, true);
        CompoundBorder compound = new CompoundBorder(line, border);
        for (int i = 0; i <12; i++) {
            JLabel label = new JLabel("Label" + i);
            label.setBorder(compound);
           // label.setBounds(13, 100, 100, 50);
           jPanel1.add(label);
        }
        return jPanel1;
    }



    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(204, 0, 153));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 306, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 243, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 94, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }                      


    public static void main(String args[]) {


        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Testing1().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}

updated Thanks in advance

user3456343
  • 252
  • 3
  • 7
  • 21
  • 1
    Read [how to use `LayoutManager`](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html). – alex2410 Mar 26 '14 at 06:55
  • _"How to give spaces between jlabel?"_ - `setBounds`: no; Use `EmptyBorders`: yes; Use LayoutManagers with gaps: yes – Paul Samsotha Mar 26 '14 at 06:57
  • @peeskillet..how can i use this can u explain little bit – user3456343 Mar 26 '14 at 06:59
  • add your full code..are you asking about giving spaces between your labels named **Case,Item and CourtNo** .. – Prakash Mar 26 '14 at 07:11
  • @prakash i have updated my full code – user3456343 Mar 26 '14 at 07:18
  • @user3456343 in this exactly where you need spaces between lables.can you explain clearly.. – Prakash Mar 26 '14 at 07:23
  • when i run this program then it is working – user3456343 Mar 26 '14 at 07:24
  • but i want that when jlabel create at run time it should contain spaces among every jlabel – user3456343 Mar 26 '14 at 07:25
  • Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). And yes, all this can be done with the Netbeans GUI builder, if you know how. Until then, it is ***better to stick with coding by hand.*** – Andrew Thompson Mar 26 '14 at 08:37

2 Answers2

6

"How to give spaces between jlabel?"

setBounds and null layouts: no; Use EmptyBorders: YES!; Use LayoutManagers: YES!

"how can i use this can u explain little bit "

Use can use the default FlowLayout of the containing JPanel (or in this case set the gaps of the FlowLayout)

FlowLayout constructor:

public FlowLayout(int align,
      int hgap,
      int vgap)

align - the alignment value

hgap - the horizontal gap between components and between the components and the borders of the Container

vgap - the vertical gap between components and between the components and the borders of the Container

Example

JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 5);
for (int i = 0; i < 10; i++) {
    panel.add(new JLabel("Label" + i));
}

You could use EmptyBorder

EmptyBorder constructor

public EmptyBorder(int top,
       int left,
       int bottom,
       int right)

top - the top inset of the border

left - the left inset of the border

bottom - the bottom inset of the border

right - the right inset of the border

Example

JPanel panel = new JPanel();
for (int i = 0; i < 10; i++) {
    JLabel label = new JLabel("Label" + i);
    EmptyBorder border = new EmptyBorder(5, 20, 5, 20);
    label.setBorder(border);
    panel.add(label);
}

If you want to use a LineBorder and an EmptyBorder for margins, you can use a CompoundBorder

A composite Border class used to compose two Border objects into a single border by nesting an inside Border object within the insets of an outside Border object. For example, this class may be used to add blank margin space to a component with an existing decorative border:

CompoundBorder Example

JPanel panel = new JPanel();
EmptyBorder border = new EmptyBorder(5, 20, 5, 20);
LineBorder line = new LineBorder(Color.blue, 2, true);
CompoundBorder compound = new CompoundBorder(line, border);
for (int i = 0; i < 10; i++) {
    JLabel label = new JLabel("Label" + i);
    label.setBorder(compound);
    panel.add(label);
}

There is an abundant number possibilities. Choose your flavor. The whole point it no not try and set size and position to everything, and make use of layout managers and borders and gaps for sizing, spacing etc.

Learn to use the different layout managers at Laying out Components Within a Container


Full example using CompoundBorder and GridLayout(int rows, int cols, int hgap, int vgap)

enter image description here

import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

public class CompoundBorderDemo {

    public CompoundBorderDemo() {
        JFrame frame = new JFrame();
        JPanel panel = createPanel();
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private JPanel createPanel() {
        JPanel panel = new JPanel(new GridLayout(5, 5, 10, 10));
        EmptyBorder panelBorder = new EmptyBorder(10, 10, 10, 10);
        panel.setBorder(panelBorder);
        EmptyBorder border = new EmptyBorder(5, 20, 5, 20);
        LineBorder line = new LineBorder(Color.blue, 2, true);
        CompoundBorder compound = new CompoundBorder(line, border);
        for (int i = 0; i < 25; i++) {
            JLabel label = new JLabel("Label" + i);
            label.setBorder(compound);
            panel.add(label);
        }
        return panel;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new CompoundBorderDemo();
            }
        });
    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • i used compoundborder example it is not creating any jlable at run time – user3456343 Mar 26 '14 at 07:28
  • If you set the layout to null, you have to remove that. null layouts require setting bounds, which I don't recommend – Paul Samsotha Mar 26 '14 at 07:30
  • Also JFrame has a default BorderLayout. You can't just `add` multple components to it, or else only on will appear. Instead add the labels to a panel with its default flowlayout, and add the panel to the frame – Paul Samsotha Mar 26 '14 at 07:32
  • i am not using null layout – user3456343 Mar 26 '14 at 07:33
  • Ok, see my example I just posted – Paul Samsotha Mar 26 '14 at 07:38
  • If you want to add the labels directly to the frame, then you need to change the layout of the frame. You can do so by right clicking on the frame and select Set Layout. Or you can just just drag a JPanel for the frame and set the layout of _that_ panel then add the labels to the panel – Paul Samsotha Mar 26 '14 at 07:49
  • one more question is that how can i start creating label from specified location – user3456343 Mar 26 '14 at 07:55
  • You're using a GUI Builder tool, why not just place them manually where you want them? That's what the tool is for. The `GroupLayout` let's you do that. If you want to hand code, then you should use the appropriate layout managers. You can nest multiple panels with different layout managers to get your desired result. Also look into `GridBagLayout` for more precision. Other than that, I can't really offer much more help. If you want exact positioning, you need a null layout where you can set bounds, but I in no way recommend that. – Paul Samsotha Mar 26 '14 at 07:59
  • How can i add jpanel at given position – user3456343 Mar 26 '14 at 08:30
  • You're using the GUI Builder tool aren't you? Just drag and drop it. – Paul Samsotha Mar 26 '14 at 08:31
  • What you want to do with the panel you drag and dropped is just add a new panel to it. The panel you drag and dropped should already have a locastion, so you dont need to set it. Instead set the layout of the panel you dragged to `BorderLayout`. Then create a new JPanel with the method, and add that panel to the one you drag and dropped – Paul Samsotha Mar 26 '14 at 08:49
  • i want to put your given code inside this panel only – user3456343 Mar 26 '14 at 08:54
  • I Know So leave the method the way I had it. Don't change it at all. Then `JPanel panel = createPanel(); jPanel1.setLayout(new GridBagLayout()); jPanel1.add(panel);` – Paul Samsotha Mar 26 '14 at 08:57
  • or `jPanel1.setLayout(new BorderLayout());`. `BorderLayout` will stretch the `panel` to fit, `GridBagLayout` will respect the preferred size of the `panel` – Paul Samsotha Mar 26 '14 at 08:59
  • Also _why_ are you creating another frame. Your class is already a frame. Take all that frame code out. – Paul Samsotha Mar 26 '14 at 09:01
  • i did this JPanel panel = createPanel(); jPanel1.setLayout(new GridBagLayout()); jPanel1.add(panel); – user3456343 Mar 26 '14 at 09:12
  • Did you change the method back to how it was? I see in your code that you changed it. And is `jPanel1` the panel that you drag and dropped? It works fine for me. I just tested it with GUI Builder – Paul Samsotha Mar 26 '14 at 09:13
  • i did not make any change in method – user3456343 Mar 26 '14 at 09:17
  • i made change in contructer – user3456343 Mar 26 '14 at 09:18
  • You _DID_ make changes. You changed `JPanel panel` to `jPanel1`, and all the others. – Paul Samsotha Mar 26 '14 at 09:19
  • 1
    @peeskillet no s/he waiting for miracle +1 – mKorbel Mar 26 '14 at 09:20
  • This will be the last comment I will give you. I am not a help desk, sorry. So **1.** Start _all_ over by creating a new `JFrame` form. **2.** Drag and drop an `JPanel` to it (`jPanel1`) **3.** Copy and paste my method from this answer _exactly_ and don't change it. **4.** in the constructor use `JPanel panel = createPanel(); jPanel1.setLayout(new GridBagLayout()); jPanel1.add(panel);`. That _must_ work, as I have just tested it. Bye and Godspeed. – Paul Samsotha Mar 26 '14 at 09:24
  • @peeskillet sory to troubled u but i am too much confused can u send more specific code – user3456343 Mar 26 '14 at 09:25
  • i am doing exactly here is not workin only jPanel1.add(panel); – user3456343 Mar 26 '14 at 09:29
  • @peeskillet help me i am getting troubled here jPanel1.setLayout(new GridBagLayout()); jPanel1.add(panel); – user3456343 Mar 26 '14 at 09:37
  • You have to do that _after_ `initComponents`. `initComponent` is where `jPanel1` is initialized. Also make sure your panel that you dragged a dropped is actually named `jPanel1`. This is all basic stuff. If you can't figure it out from here, I'm sorry, but I can no longer help you. – Paul Samsotha Mar 26 '14 at 09:40
2

Try using layouts like GridLayout instead of setting bounds to every label.

it is the simplest solution for your problem.Grid Layout May suit you better.

refer the links below for that..

GRID LAYOUT

Prakash
  • 693
  • 5
  • 17