2017-02-02 79 views
-2

我想創建一個紅色JButton顏色設定爲一個JButton不調整邊框

import java.awt.*; 
import javax.swing.*; 

public class RedButtonTest { 
    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       JFrame frame = new JFrame("Red Button Color Test"); 
       JPanel pane1 = new JPanel(new FlowLayout()); 
       JPanel pane2 = new JPanel(new FlowLayout()); 
       JButton button1 = new JButton(); 
       JButton button2 = new JButton(); 

       frame.setSize(new Dimension(300, 300)); 
       button1.setPreferredSize(new Dimension(100, 100)); 
       button2.setPreferredSize(new Dimension(100, 100)); 
       button2.setBackground(Color.red); 
       button2.setBorderPainted(false); //This line 
       button2.setOpaque(true); 

       pane1.add(button1); 
       pane2.add(button2); 
       frame.add(pane1, BorderLayout.WEST); 
       frame.add(pane2, BorderLayout.EAST); 

       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 
} 

有沒有一種方法,使按鈕的紅色,而無需使用

setBorderPainted(false); 

當不使用時,邊界變紅而不是按鈕本身,但是,我不想使用這一行,因爲它刪除了按鈕的軟邊緣。是否有另一種顏色按鈕的方法?

+0

替代解決方案:可以繪製邊框的顏色選擇這樣的: button2.setBorder(BorderFactory.createLineBorder(Color.black)); –

+0

答案已經在其他帖子中給出,這是一個LAF問題。這個問題沒有提到這個信息。如果您使用Mac並瞭解解決方案,請查看其他信息。把所有關於這個問題的信息放在一起,這樣每個人都知道已經討論和建議的內容。 – camickr

回答

0

嘗試使用button2.setContentAreaFilled(false);。這將保持邊緣但設置背景顏色。根據docs

如果爲true,則該按鈕將繪製內容區域。例如,如果您希望有一個透明按鈕(例如僅圖標按鈕),那麼您應該將其設置爲false。不要調用setOpaque(false)。 contentAreaFilled屬性的默認值 值爲true。

+0

對不起,這不起作用。如果你嘗試在上面的例子中插入這一行,你會發現右邊的按鈕(帶有這行代碼的那一行)變成了一個紅色的方形按鈕,而不是一個帶有軟邊緣的紅色按鈕。 – Playdowin