按钮失去焦点: 按钮有焦点:
简短代码:
MLibrary = new JButton();
MenuPane.add(MLibrary, new AnchorConstraint(0, 0, 0, 0, AnchorConstraint.ANCHOR_ABS, AnchorConstraint.ANCHOR_NONE, AnchorConstraint.ANCHOR_ABS, AnchorConstraint.ANCHOR_ABS));
MLibrary.setText("Library");
setButtonDefaults(MLibrary);
MScheduler = new JButton();
MenuPane.add(MScheduler, new AnchorConstraint(0, 0, 0, 110, AnchorConstraint.ANCHOR_ABS, AnchorConstraint.ANCHOR_NONE, AnchorConstraint.ANCHOR_ABS, AnchorConstraint.ANCHOR_ABS));
MScheduler.setText("Scheduler");
setButtonDefaults(MScheduler);
private void setButtonDefaults(JButton but) { //calls in JPanel init only for setting button defaults
but.setBorderPainted(false);
but.setBackground(Color.DARK_GRAY);
but.setForeground(Color.WHITE);
but.setName(but.getText().toLowerCase());
but.setPreferredSize(buttonSize);
but.addActionListener(this);
}
private void enableOnlyOne(JButton but) {//calls each time when one of menu buttons are pressed. but is pressed button
// TODO Auto-generated method stub
setButtonDisabled(MLibrary);
setButtonDisabled(MScheduler);
setButtonDisabled(MBudget);
setButtonDisabled(MReports);
setButtonDisabled(MManage);
setButtonDisabled(MSettings);
//enable one
//but.setFocusPainted(true);
but.getModel().setPressed(true);
but.setBackground(ContentPane.getBackground());
but.setForeground(Color.BLACK);
}
private void setButtonDisabled(JButton but) { //sets button unpressed
but.getModel().setPressed(false);
but.setBackground(Color.DARK_GRAY);
but.setForeground(Color.WHITE);
}
所以,我的问题是如何编码每个按钮,当按钮失去焦点时,它将是浅灰色背景,而不是默认外观
答案 0 :(得分:3)
为每个按钮添加 Focus Listener 并实现功能public void focusLost(FocusEvent e)
,并在功能内部设置按钮的背景。
来源: http://docs.oracle.com/javase/tutorial/uiswing/events/focuslistener.html
<强>更新强>
在focusLost(FocusEvent e)
内,输入以下代码:
JButton button = (JButton) e.getSource();
e.setBackground(Color.Gray);