Несмотря на мои усилия по изменению цвета моих кнопок и чтению повсюду о том, как это сделать, мой код по-прежнему не дает желаемого эффекта. Как я могу изменить цвет JButton при нажатии?
public void generateButtons
{
//Global field
firstBoard = new JButton[9][9];
for(int x = 0; x < firstBoard.length; x++)
{
for(int y = 0; y < firstBoard[0].length; y++)
{
firstBoard[x][y] = new JButton();
firstBoard[x][y].setActionCommand("0|" + (x + (firstBoard.length * y)));
firstBoard[x][y].addActionListener(this);
//firstBoardPanel.add(firstBoard[x][y]);
}
}
}
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() instanceof JButton )
{
System.out.println(parseActionCommand(((JButton)e.getSource()).getActionCommand()));
((JButton)e.getSource()).setBackground(Color.BLUE);
((JButton)e.getSource()).setContentAreaFilled(false);
((JButton)e.getSource()).setOpaque(true);
}
}
Это не ответ, а расширенный тестовый пример, чтобы проверить разницу между Mac OS Look и Feel и Nimbus, который при работе в ОС Windows работает
Похоже, это стало ответом...
Попробуйте это, чтобы начать с...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
public class ChangeButton {
public static void main(String[] args) {
new ChangeButton();
}
public ChangeButton() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel implements ActionListener {
private final JButton[][] firstBoard;
public TestPane() {
setLayout(new GridLayout(9, 9));
firstBoard = new JButton[9][9];
for (int x = 0; x < firstBoard.length; x++) {
for (int y = 0; y < firstBoard[0].length; y++) {
firstBoard[x][y] = new JButton();
firstBoard[x][y].setActionCommand("0|" + (x + (firstBoard.length * y)));
firstBoard[x][y].addActionListener(this);
add(firstBoard[x][y]);
}
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
System.out.println((((JButton) e.getSource()).getActionCommand()));
((JButton) e.getSource()).setBackground(Color.BLUE);
((JButton) e.getSource()).setContentAreaFilled(false);
((JButton) e.getSource()).setOpaque(true);
}
}
}
}
Затем замените UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
с этим...
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
И попробуй еще раз
Попробуйте перекрасить контейнер, содержащий эту кнопку.
button.getParent().validate();
button.getParent().repaint();
revalidate
был бы лучшим методом, и когда я тестировал его, используя Windows, Metal и Nimbus, он не требовался ...
Не используйте напрямую e.getSource()
вам нужно сначала ссылаться на объект, и использовать его:
пример:
ublic void actionPerformed(ActionEvent e)
{
Object ob = e.getSource();
if(ob instanceof JButton )
{
System.out.println(parseActionCommand(((JButton)e.getSource()).getActionCommand()));
JButton button = ((JButton)ob);
button.setBackground(Color.BLUE);
button.setContentAreaFilled(false);
button.setOpaque(true);
}