JFRAME上的JAVA定位标签 [英] JAVA positioning labels on JFRAME

查看:185
本文介绍了JFRAME上的JAVA定位标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要绘制一个水平直方图,并且按如下所示设置直方图的标签,

I need to draw a horizontal histogram, and i am setting up the labels of the histogram as follows,

public static void drawVertical(){

 JFrame frame = new JFrame("Horizontal Histogram");
 frame.setSize(300, 300);
 frame.setVisible(true);
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      


 JLabel label_01=new JLabel("0-29");  
 label_01.setAlignmentX(-290);
 label_01.setAlignmentY(290);

 JLabel label_02=new JLabel("30-39"); 
 label_02.setAlignmentX(-290);
 label_02.setAlignmentY(270);

 JLabel label_03=new JLabel("40-69"); 
 label_03.setAlignmentX(-290);
 label_03.setAlignmentY(250);

 JLabel label_04=new JLabel("70-100"); 
 label_04.setAlignmentX(-290);
 label_04.setAlignmentY(230);

 frame.add(label_01);
 frame.add(label_02)
 frame.add(label_03);
 frame.add(label_04);
 }

但这是我得到的输出:(

But this is the output i get :(

这是我的预期输出(用MS paint编辑)

And this is my expected output (Edited with MS paint),

有人能找出这里有什么问题吗?
为什么不显示其他标签?

Can anyone figure out whats wrong here?
Why arent the other labels being displayed?

推荐答案

此问题的答案是,您不应使用BorderLayout(默认情况下JFrame使用BorderLayout),而应使用GridLayout .这将允许您仅将JLabels添加到您的JFrame中.一个示例如下所示:

The answer to this question is that you should not use a BorderLayout (which the JFrame uses by default), but instead use a GridLayout. This will allow you to just add the JLabels to your JFrame. An example looks like this:

EventQueue.invokeLater(() -> {
    JFrame frame = new JFrame("Stackoverflow | Question");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setLocationRelativeTo(null);
    // This is the important line. This will Change the layout to a GridLayout.
    frame.setLayout(new GridLayout(4, 1));
    frame.add(new JLabel("0-29"));
    frame.add(new JLabel("30-39"));
    frame.add(new JLabel("40-69"));
    frame.add(new JLabel("70-100"));
    frame.setVisible(true);
});

这篇关于JFRAME上的JAVA定位标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆