当前位置: 代码迷 >> J2SE >> 为什么label无法显示?解决方案
  详细解决方案

为什么label无法显示?解决方案

热度:100   发布时间:2016-04-24 01:00:39.0
为什么label无法显示?
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;


public class SelectPosition extends JFrame{


private final BorderLayout borderLayout = new BorderLayout();
private final JPanel panel = new JPanel();
private final JLabel label = new JLabel();
public static void main(String[] args) {
SelectPosition frame = new SelectPosition();
frame.setVisible(true);
}

public SelectPosition() {
super();
setTitle("控制内容的对齐方式 ");
setBounds(100, 100, 500, 375);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


panel.setLayout(borderLayout);
getContentPane().add(panel, BorderLayout.NORTH);


label.setText("请注意我的位置啊!");

JPanel southPanel = new JPanel();
getContentPane().add(southPanel, BorderLayout.CENTER);

ButtonGroup group = new ButtonGroup();

final JRadioButton leftButton = new JRadioButton();
leftButton.setText("靠左侧显示");
group.add(leftButton);
southPanel.add(leftButton);
leftButton.addActionListener(new leftActionListener());

final JRadioButton middleButton = new JRadioButton();
middleButton.setText("居中显示");
middleButton.setSelected(true);
group.add(middleButton);
southPanel.add(middleButton);
middleButton.addActionListener(new middleActionListener());

final JRadioButton rightButton = new JRadioButton();
rightButton.setText("靠右侧显示");
group.add(rightButton);
southPanel.add(rightButton);
rightButton.addActionListener(new rightActionListener() );
}

class middleActionListener implements ActionListener {
public void actionPerformed(ActionEvent e){
panel.add(label, BorderLayout.CENTER);
}


}
class rightActionListener implements ActionListener {
public void actionPerformed(ActionEvent e){
panel.add(label, BorderLayout.EAST);
}
}

class leftActionListener implements ActionListener {
public void actionPerformed(ActionEvent e){
panel.add(label, BorderLayout.WEST);
}
}

}

------解决方案--------------------
由于你的panel只有一个label,所以使用BorderLayout布局的时候,无论是在north,south,center都是默认占据了整个panel,建议创建三个label对象,分别设为east,center,west,然后按钮的消息响应事件就设置对应的label的setVisible(true),其他的设为false就行了,试过可行了
------解决方案--------------------
监听类的方法里加pack();方法。panel.add(label, BorderLayout.CENTER);这句后面。这样会改变窗体大小。你看一下pacK()方法是干什么的。
  相关解决方案