在編寫 Swing 介面時,按鈕獲得焦點後,文字四周會出現一個虛線矩形框,影響美觀。
只需呼叫 JButton.setFocusPainted(false) 即可關閉焦點繪製。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Demo");
JButton button = new JButton("JB");
button.addActionListener(e -> System.out.println("click JB"));
// 關鍵:去掉焦點邊框
button.setFocusPainted(false);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 200, 136);
frame.setVisible(true);
}
}
註解掉該行即可對比前後效果,簡單有效。