无法在JPanel上设置JLabel的位置

Joh*_*son 6 java swing jlabel jpanel

我已经为JLabel设置了相对于JPanel的位置(0,0).但它正在中心和顶部.我犯了什么错误?

import java.awt.*; 
import javax.swing.*; 
import java.awt.event.*;
public class Main extends JFrame 
{ 
private JPanel panel;
private JLabel label1;
public Main() 
{ 
    panel = new JPanel(); 
    panel.setBackground(Color.YELLOW); 

    ImageIcon icon1 = new ImageIcon("3.png"); 
    label1 = new JLabel(icon1); 
    label1.setLocation(0,0); 
    panel.add(label1);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.getContentPane().add(panel); 
    this.setSize(500,500); 
    this.setVisible(true); 

} 

public static void main (String[] args) {
    new Main(); 
} 
} 
Run Code Online (Sandbox Code Playgroud)

小智 8

将布局管理器设置null为对我不起作用.试试这个:

// setLocation(0,0); //remove line.
panel.setLayout(new FlowLayout(FlowLayout.LEFT)); // change from 'centered'
Run Code Online (Sandbox Code Playgroud)

瞧!:)我建议你看看新RelativeLayout经理.


And*_*son 8

使用布局!

左对齐图像图标的屏幕截图

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

public class Main extends JFrame
{
    private JPanel panel;
    private JLabel label1;

    public Main() throws Exception
    {
        // Do use layouts (with padding & borders where needed)!
        panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        panel.setBackground(Color.YELLOW);

        URL url = new URL("http://pscode.org/media/starzoom-thumb.gif");
        ImageIcon icon1 = new ImageIcon(url);

        label1 = new JLabel(icon1);
        // Don't use null layouts, setLocation or setBounds!
        //label1.setLocation(0,0);
        panel.add(label1);
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().add(panel);
        setSize(400,200);
        setLocationByPlatform(true);
        setVisible(true);
    }

    public static void main (String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    new Main();
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

更新

对这个帖子的回复似乎有很多混淆,所以澄清一件事:

  • A 默认JPanel有一个FlowLayout.
  • FlowLayout它得到,来自"无参数的构造函数,如1. new FlowLayout()
  • 产生的no-args构造函数FlowLayout..

    (1)..一个新的FlowLayout,具有居中对齐和默认的5单位水平和垂直间隙.

  • 1)查看编辑.2)使用no-args构造函数(例如默认面板). (4认同)