Question

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.

Was it helpful?

Solution

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());

OTHER TIPS

Try RelativeLayout library. A tutorial is here at Wiki.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top