在这里我实现了JButton
:
btnTotalCall = new JButton("Total calls");
btnTotalCall.setFocusPainted(false);
btnTotalCall.setVerticalAlignment(SwingConstants.TOP);
btnTotalCall.setForeground(Color.BLACK);
btnTotalCall.setBackground(Color.WHITE);
btnTotalCall.setBounds(302, 39, 125, 125);
contentPane.add(btnTotalCall);
这里有一个JLabel
:
lblTotalCall = new JLabel("");
lblTotalCall.setHorizontalAlignment(SwingConstants.CENTER);
lblTotalCall.setBackground(Color.WHITE);
lblTotalCall.setForeground(Color.BLACK);
lblTotalCall.setFont(new Font("Tahoma", Font.BOLD, 20));
lblTotalCall.setBounds(302, 39, 125, 125);
contentPane.add(lblTotalCall);
在MainController
中,我试图用我的数据库更新lblTotalCall
所有秒:
public MainController(MainView mainView)
{
this.mainView = mainView;
ActionListener timerListener = new ActionListener()
{
DAO<Call> call_dao = new CallDAO();
List<Call> call_list;
int call_time;
DAO<User> user_dao = new UserDAO();
List<User> user_list;
public void actionPerformed(ActionEvent e)
{
// Put the current date and time in the label date and update it
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
DateFormat heureFormat = new SimpleDateFormat("HH:mm:ss");
Date cal = Calendar.getInstance().getTime();
mainView.getLblDate().setText("<html>" + dateFormat.format(cal).toString() + "<br>" +
heureFormat.format(cal) + "</html>");
call_list = call_dao.recupAll();
// Update the lblTotalCall
if(call_list.size() > 0)
{
mainView.getLblTotalCall().setText(Integer.toString(call_list.size()));
}
else
{
mainView.getLblTotalCall().setText("0");
}
for (Call call : call_list)
{
if (call.getDate() == cal && mainView.getRdbtnToday().isSelected())
{
call_time = call_time + call.getDuration();
call_time = call_time / call_list.size();
}
}
user_list = user_dao.recupAll();
if(user_list.size() > 0)
{
mainView.getLblOperators().setText(Integer.toString(user_list.size()));
}
else
{
mainView.getLblOperators().setText("0");
}
}
};
Timer timer = new Timer(1000, timerListener);
// to make sure it doesn't wait one second at the start
timer.setInitialDelay(0);
timer.start();
}
我已经尝试在JLabel
中设置一个默认值,并将属性focusable
和enabled
的值更改为false,但这并不能解决问题。
我启动了应用程序,(抱歉,我无法发布图片)
我看到了正确的数据但是当我将鼠标指针放在btnTotalCall
或btnOperators
上时,标签会消失。
我试着把Jlabel放在Jbutton上
我只看到:
contentPane.add(btnTotalCall);
...
contentPane.add(lblTotalCall);
这意味着您要向面板添加两个组件,而不是向按钮添加标签。
但是当我把我的鼠标指针放在jlabel上时就消失了
默认情况下,Swing假定组件不重叠,当您将鼠标移到按钮上时,需要重新绘制按钮以将鼠标绘制在按钮的效果上,因此整个按钮将重新绘制,您不再看到标签。
如果要在同一位置绘制两个组件,则需要覆盖面板的isOptimizedDrawingEnabled()
方法以返回false
以确保重新绘制两个组件。
请参阅:Overlap Layout用于布局管理器,一旦覆盖上述方法,它将允许您将多个组件堆叠在一起。
或者更简单的方法是将标签添加到按钮:
JButton button = new JButton("Total Calls");
button.setVerticalAlignment(SwingConstants.TOP);
button.setLayout( new BorderLayout() );
JLabel center = new JLabel("0");
center.setHorizontalAlignment(SwingConstants.CENTER);
button.add(center, BorderLayout.CENTER);
这不是真正的布局管理器,因为按钮的大小仅由按钮的属性决定,而不是由添加到按钮的标签决定。
另一种选择是使用HTML作为按钮的文本:
JButton button2 = new JButton("<html>Total Calls<br><br><center>0</center></html>");