Search code examples
javaswingborderjbutton

Java Swing Focus Border too small


Let me start by saying that I am very confused that there is no answer for this question on stackoverflow - at least i didn't find one. So I guess my problem has to quite specific although I don't get why. This question was already asked similarly over 1 year ago here

The question has not been answered and because it is so old I will ask it again. I don't have any metal design going on as in the original question, all I'm doing is creating a simple button inside of a panel (I'm using eclipse to design the application) but the focus border only wraps around the text and does not scale with the size of the button but only with the size of the font.

Here is my whole design code (its not much since I just started)

    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 1000, 500);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JPanel MainPanel = new JPanel();
    MainPanel.setFocusCycleRoot(true);
    MainPanel.setBackground(Color.DARK_GRAY);
    MainPanel.setBounds(0, 0, 995, 465);
    contentPane.add(MainPanel);
    MainPanel.setLayout(null);

    JButton StartButton = new JButton("Launch Oasis");
    StartButton.setBorder(new LineBorder(Color.BLACK));
    StartButton.setBackground(new Color(169, 169, 169));
    StartButton.setForeground(new Color(0, 128, 128));
    StartButton.setBounds(397, 197, 200, 50);
    StartButton.setFont(new Font("Times New Roman", Font.PLAIN, 30));
    MainPanel.add(StartButton);

This is the button I'm talking about

I want to stress the same thing the original author did, I want the focus border to be painted so jButton.setFocusPainted(false); wouldn't solve my problem. Is there any obvious reason for the focus border no scaling with the size of the button?


Solution

  • This answer contains my research in response to camickr's provided sources.

    Change the Look and Feel of your application to the Windows Look and Feel by adding the following to your main method before creating the JFrame. For it to work you'll need to import javax.swing.UIManager;:

    try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (Exception e) {
            System.out.println("Error");
        }
    

    This will give you a focus border next to the button border wrapping around the whole button. Note that this method can throw a bunch of Exceptions (ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException). For further information on this topic, you can visit the Modifying the Look and Feel section of the swing tutorial.