当按钮失去焦点时显示默认的JButton [英] Appears default JButton when button looses focus

查看:141
本文介绍了当按钮失去焦点时显示默认的JButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按钮失去焦点: 按钮具有焦点:

Button lost focus: Button has focus:

短代码:

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);
}

所以,我的问题是如何对每个按钮进行编码,当按钮失去焦点时,背景应该是浅灰色,而不是默认外观

So, my question is how to code each button, when button looses focus, it would be with light grey background, not default appearance

推荐答案

向每个按钮添加焦点侦听器,并实现功能public void focusLost(FocusEvent e),并在该函数内部设置按钮的背景.

Add a Focus Listener to each button and implement the function public void focusLost(FocusEvent e) and inside thie function set the background of the buttons.

来源: http://docs .oracle.com/javase/tutorial/uiswing/events/focuslistener.html

更新:

focusLost(FocusEvent e)内,输入以下代码:

JButton button = (JButton) e.getSource();
e.setBackground(Color.Gray);

这篇关于当按钮失去焦点时显示默认的JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆