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经理.

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)
对这个帖子的回复似乎有很多混淆,所以澄清一件事:
JPanel有一个FlowLayout. FlowLayout它得到,来自"无参数的构造函数,如1. new FlowLayout()FlowLayout..
(1)..一个新的FlowLayout,具有居中对齐和默认的5单位水平和垂直间隙.
| 归档时间: |
|
| 查看次数: |
33298 次 |
| 最近记录: |