Placing a JLabel at a specific x,y coordinate on a JPanel

前端 未结 6 636
梦毁少年i
梦毁少年i 2020-12-05 16:12

I\'m trying to place a series of JLabels at specific X and Y coordinates on a JPanel (and set its height and width, too). No matter what I do, each label winds up immediatel

6条回答
  •  时光取名叫无心
    2020-12-05 16:43

        // Best solution!!
    
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    public class Main {
    
      public static void main(String args[]) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        JPanel panel = (JPanel) frame.getContentPane();
        panel.setLayout(null);
    
        JLabel label = new JLabel("aaa");
        panel.add(label);
        Dimension size = label.getPreferredSize();
        label.setBounds(100, 100, size.width, size.height);
    
        frame.setSize(300, 200);
        frame.setVisible(true);
    
      }
    }
    

提交回复
热议问题