将JLabel放置在JPanel上的特定x,y坐标上

我正在尝试在JPanel上的特定X和Y坐标处放置一系列JLabel(并设置其高度和宽度)。 无论我做什么,每个标签都会立即卷到前一个标签的右侧,并且与所有其他标签的尺寸完全相同。

现在,我的Jpanel处于网格布局中。 我尝试过Absolute Layout(非法参数exception结果),Free Design(没有标签出现),Flow Layout(一切都被挤到中心),以及其他一些。

不知道我需要做些什么来使这项工作。 有人可以帮忙吗? 谢谢!

JLabel lbl1 = new JLabel("label 1"); JLabel lbl2 = new JLabel("label 2"); JLabel lbl3 = new JLabel("label 3"); JLabel lbl4 = new JLabel("label 4"); JLabel lbl5 = new JLabel("label 5"); myPanel.add(lbl1); myPanel.add(lbl2); myPanel.add(lbl3); myPanel.add(lbl4); myPanel.add(lbl5); lbl1.setLocation(27, 20); lbl2.setLocation(123, 20); lbl3.setLocation(273, 20); lbl4.setLocation(363, 20); lbl5.setLocation(453, 20); lbl1.setSize(86, 14); lbl2.setSize(140, 14); lbl3.setSize(80, 14); lbl4.setSize(80, 14); lbl5.setSize(130, 14); 

您必须将容器的布局设置为null:

 myPanel.setLayout(null); 

不过也是一个很好的建议,看看马蒂斯布局管理器,我想它现在叫做GroupLayout。 绝对定位的主要问题是当窗口改变其大小时会发生什么。

  1. 通过调用setLayout(null)将容器的布局管理器设置为null。

  2. 为每个容器的子setbounds调用Component类的setbounds方法。

  3. 调用Component类的重绘方法。

注意:

如果调整包含容器的窗口大小,则使用绝对定位的容器创建容器会导致问题。

请参阅此链接: http : //docs.oracle.com/javase/tutorial/uiswing/layout/none.html

布局管理器用于自动确定容器中组件的布局。 如果要将组件放在特定的坐标位置,则根本不应使用布局管理器。

 myPanel = new JPanel(null); 

要么

 myPanel.setLayout(null); 

我的建议是使用像NetBeans这样的IDE及其GUI编辑器。 要检查代码,因为有很多方法:

设置布局管理器,或者执行myPanel.setLayout(null)的绝对定位有几个影响。

通常,假设您在JFrame的构造函数中进行调用,可以调用pack()来开始布局。

然后,每个布局管理器都使用自己的add(Component)add(Component, Constraint) 。 BorderLayout的用法是使用add(label,BorderLayout.CENTER)等。

  // 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); } } 

您可以使用自己的方法来调用setSize,直接调用setLocation值…. “我还告诉你如何使用JProgress Bar

 import java.awt.*; import java.awt.event.*; import javax.swing.*; class installComp{ void install(Component comp, int w, int h, int x, int y){ comp.setSize(w,h); comp.setLocation(x,y); } } class MyFrame extends JFrame{ int cur_val = 0; JButton btn = new JButton("Mouse Over"); JProgressBar progress = new JProgressBar(0,100); MyFrame (){ installComp comp=new installComp(); comp.install(btn,150,30,175,20); comp.install(progress,400,20,50,70); btn.addMouseListener(new MouseAdapter(){ public void mouseEntered(MouseEvent evt){ cur_val+=2; progress.setValue(cur_val); progress.setStringPainted(true); progress.setString(null); } }); add(btn); add(progress); setLayout(null); setSize(500,150); setResizable(false); setDefaultCloseOperation(3); setLocationRelativeTo(null); setVisible(true); } } class Demo{ public static void main(String args[]){ MyFrame f1=new MyFrame(); } }