Appears default JButton when button looses focus

旧时模样 提交于 2019-12-14 02:29:53

问题


Button lost focus:

Button has focus:

Short code:

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


回答1:


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.

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

UPDATE:

Inside the focusLost(FocusEvent e), put the following code:

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


来源:https://stackoverflow.com/questions/8780378/appears-default-jbutton-when-button-looses-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!