Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding more labels in java

Hello fellow programmers! I'm trying to add two JLabel to JFrame but the second add method that added the label seems to have overwritten my first add method. I tried solving this problem by using 2 different label variables and using setLocation method providing different coordinate point for each label. But I can't seem to solve it. Why can't I add two labels in my program? By the way, I am not getting any errors. seems to be more of a logical error I can't seem to solve.

Here's my current code:

import javax.swing.*;

public class test {

    private static  JLabel label;

    private static  JLabel label1;
    public static void main(String[] args){
        initializeLabel();
        initializeImage();
        initializeFrame();
    }

    private static void initializeLabel(){
         label = new JLabel();
         label.setText("hi");
         label.setLocation(54,338);
    }

    private static void initializeImage(){
        label1 = new JLabel();
        label1.setText("sss");
        label1.setLocation(55, 340);
    }

    private static void initializeFrame(){
        JFrame frame = new JFrame();
        frame.add(label1);
        frame.add(label);

        frame.setVisible(true);
    }

}// class
like image 328
Nicholas Kong Avatar asked Dec 06 '22 18:12

Nicholas Kong


2 Answers

Change your code following way.

private static void initializeFrame(){
    JFrame frame = new JFrame();

    frame.setLayout(new FlowLayout()); // <-- you need this for now

    frame.add(label1);
    frame.add(label);
    frame.setVisible(true);

    // optional, but nice to have.
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
}

Please study more on swing layout here: A Visual Guide to Layout Managers

For more: Creating a GUI With JFC/Swing

like image 102
Kowser Avatar answered Jan 07 '23 04:01

Kowser


Read up on Layout Managers. The default layout manager for a frame is the BorderLayout. Your code is adding both labels to the CENTER of the layout. This is not possible. Each location on the BorderLayout can only contain a single component (it could be a JPanel with other components).

You need to use a different layout manager. Without knowing your exact requirement it is hard to suggest which layout manager to use.

Also, get rid of all those static methods. The Swing tutorial has plenty of example that will give you a better idea of how to structure you program.

like image 20
camickr Avatar answered Jan 07 '23 03:01

camickr