2

I've been trying to make a JLabel that is sized relatively to the size of the window yet for some reason this JLabel is not appearing on the screen.

This is the code used in my MainGUI class which holds the basic interface:

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

public class MainGUI extends JFrame{

    JPanel core;
    GridBagConstraints c;

    JLabel[] sts;

    public MainGUI(){

       core = new JPanel(new GridBagLayout()); 
       getContentPane().add(core, BorderLayout.CENTER);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
       setSize(500, 500); 


       sts = new JLabel[10];

       int width = (int)(66/100) * getWidth(), height = (int)(75/100) * getHeight();       //problem: due to these sizes the JLabel is not appearing

       for(int i = 0; i < sts.length; i++){ 
          sts[i] = new JLabel("test");
          sts[i].setOpaque(true);
          sts[i].setBackground(Color.BLACK);
          sts[i].setForeground(Color.BLACK);
          sts[i].setPreferredSize(new Dimension(width,height)); //size being set
       }


       c = new GridBagConstraints();

       c.gridx = 0;
       c.gridy = 0;

       core.add(sts[1], c);

    }

}

Any help in finding a solution for this would be greatly appreciated, thanks in advance.

2
  • Have you tried setting a text value for the label, so that it has something to display?
    – Ash
    Apr 2, 2013 at 8:17
  • Yes, yes I have but still, nothing.
    – beur_x
    Apr 2, 2013 at 8:18

2 Answers 2

2

Few issues-

  1. Foreground and background colors are same for label
  2. You need to set some text on the label
  3. Check if preferred size is calculated correctly, as the label is displayed if that line is commented out. The height and width calculated is zero.

This will always return zero as the result of division is int-

int width = (int)(66/100) * getWidth();

Make it-

    int width = (int)(((float)66/100) * getWidth());
0
0

Try RelativeLayout library. A tutorial is here at Wiki.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.