Paulius Vindzigelskis
Paulius Vindzigelskis

Reputation: 2181

Appears default JButton when button looses focus

Button lost focus: enter image description here Button has focus: enter image description here

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

Upvotes: 1

Views: 880

Answers (1)

Adel Boutros
Adel Boutros

Reputation: 10285

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

Upvotes: 3

Related Questions