创建了一个Frame的class
添加俩个JLabel控件(label_icon和label3)
练习添加俩个图片控件
class LabelFrame extends JFrame
{ private JLabel label_icon;
private JLabel label3;
public LabelFrame()//构造器
{
Icon star=new ImageIcon("src/star.png" );
label_icon=new JLabel(null ,star ,SwingConstants.LEFT);
add(label_icon);
////////
label3=new JLabel();
label3.setText("lately set");
label3.setIcon(star);
label3.setHorizontalAlignment(SwingConstants.CENTER);
add(label3);
}
}
添加了label3控件以后,label_icon的图片就不会显示。只会显示label3
就是:只有把 add(label3); 这一行注释掉
就能显示label_icon(当然在左侧)
如何俩个控件都显示出来???是布局问题吗。。
两个按钮你需要设置布局吧,另外就是你添加lable3,它是吧lableicon覆盖了(其实它还是存在的)你可以通过尝试设置lable3的长度宽度和设置布局(可以尝试设置网格布局)。希望对你有帮助。
你都重新覆盖了,还怎么显示,要不你就大小改一下
给你个布局演示,把你的控件加进去吧。
class LabelFrame extends JFrame {
private JLabel label_icon;
private JLabel label3;
public LabelFrame()// 构造器
{
this.setTitle("布局实例");
this.setBounds(500, 200, 300, 300);
this.setLayout(new BorderLayout(10, 10));
Icon star = new ImageIcon("src/star.png");
this.add(new JButton("北"), BorderLayout.NORTH);
this.add(new JButton("东"), BorderLayout.EAST);
this.add(new JButton("南"), BorderLayout.SOUTH);
this.add(new JButton("西"), BorderLayout.WEST);
this.add(new JButton("中"));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
/*
* label3 = new JLabel(); label3.setText("lately set"); label_icon = new JLabel(null, star, SwingConstants.WEST);
* label3.setIcon(star); label3.setHorizontalAlignment(SwingConstants.CENTER); this.add(label3);
*/
}
public static void main(String[] args) {
LabelFrame lf = new LabelFrame();
}
}
可以试试在JFrame里放一个JPanel,然后add这个JPanel,再把需要的东西按需要放进这个panel就行。你可以试试下面的这种排版看是不是你想要的
class LabelFrame extends JFrame{
private JLabel label_icon;
private JLabel label3;
public LabelFrame(){
JPanel panel = new JPanel (new BorderLayout());
Icon star=new ImageIcon("src/star.png" );
label_icon=new JLabel();
label_icon.setIcon(star);
panel.add(label_icon, BorderLayout.WEST);
label3=new JLabel();
label3.setText("lately set");
label3.setIcon(star);
panel.add(label3, BorderLayout.CENTER);
add(panel);
}
}