最近无聊尝试做一款软件应用,但是在该过程中遇到个问题:
问题描述: 我创建了一个JFrame窗口后,在该窗口内添加了个Container,并使Container采用null布局,然后向该Container中添加了两个按钮(JButton),在添加第三个按钮的时候,发现运行程序后按钮不显示,只有在鼠标滑过按钮后按钮才显示出来。
原先的代码:
void addExit() {
JButton jButton = new JButton("退出");
int y = lastFuncButtonInfo.location.y + lastFuncButtonInfo.buttonSize.height + 10;
jButton.setBounds(0, y, ButtonInfo.buttonWide, ButtonInfo.buttonHeight);
setLastFunctionButtonInfo(new ButtonInfo(new Point(0, y), lastFuncButtonInfo.buttonSize));
rootContainer.add(jButton);
jButton.addMouseListener(new MyMouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
});
// rootContainer.revalidate();
this.revalidate();
}
问题解决方法:
将按钮添加的时机提前,在创建按钮后就向按钮添加到Container中
更改后代码:
void addExit() {
JButton jButton = new JButton("退出");
rootContainer.add(jButton);
int y = lastFuncButtonInfo.location.y + lastFuncButtonInfo.buttonSize.height + 10;
jButton.setBounds(0, y, ButtonInfo.buttonWide, ButtonInfo.buttonHeight);
setLastFunctionButtonInfo(new ButtonInfo(new Point(0, y), lastFuncButtonInfo.buttonSize));
jButton.addMouseListener(new MyMouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
});
}