创建一个圆形背景颜色的按钮Java

时间:2017-08-19 16:39:49

标签: java jbutton

我有以下按钮:

    JButton S1L1Reset = new JButton("Reset");
    S1L1Reset.setFont(new Font("Work Sans", Font.PLAIN, 14));
    S1L1Reset.setForeground(new Color(90, 90, 90));
    S1L1Reset.setBackground(new Color(220, 208, 192));
    S1L1Reset.setOpaque(true);

我希望按钮是圆形而不是盒装。我发现另一个帖子创建了一个类,可以使按钮的边框变圆,如下所示。

class RoundedBorder implements Border {

     private int radius;

     RoundedBorder(int radius) {
        this.radius = radius;
     }

    public Insets getBorderInsets(Component c) {
        return new Insets(this.radius+1, this.radius+1, this.radius+2, this.radius);
    }

    public boolean isBorderOpaque() {
        return true;
    }

    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        g.drawRoundRect(x, y, width-1, height-1, radius, radius);
    }
}

当我对按钮进行更改时,为了使用这个类,我得到以下代码:

    JButton S1L1Reset = new JButton("Reset");
    S1L1Reset.setFont(new Font("Work Sans", Font.PLAIN, 14));
    S1L1Reset.setForeground(new Color(90, 90, 90));
    S1L1Reset.setBackground(new Color(220, 208, 192));
    S1L1Reset.setOpaque(true);
    S1L1Reset.setBorderPainted(false);
    S1L1Reset.setBorder(new RoundedBorder(20)); //new line of code added

然而,代码会创建一个如下所示的按钮:Button。有什么方法可以格式化按钮,使背景颜色也保持在圆形边框内。

整个代码:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicButtonUI;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.JMenu;
import javax.swing.JTabbedPane;
import javax.swing.JTable;

import java.awt.CardLayout;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.Graphics;
@SuppressWarnings("rawtypes")
public class TestEnvironment {

JFrame TestEnvironmentWindow;

Vector data1 = new Vector(100);
Vector data2 = new Vector(100);
Vector data3 = new Vector(100);
JTable S1L1;
JTable S1L2;
JTable S1L3;

private DefaultTableModel dataModel1;
private DefaultTableModel dataModel2;
private DefaultTableModel dataModel3;

public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                TestEnvironment window = new TestEnvironment();
                window.TestEnvironmentWindow.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public TestEnvironment() {
    initialize();
}

private void initialize() {

    TestEnvironmentWindow = new JFrame();
    TestEnvironmentWindow.getContentPane().setLayout(null);
    TestEnvironmentWindow.setResizable(false);
    TestEnvironmentWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    TestEnvironmentWindow.setTitle("Statistics Tool Kit");
    TestEnvironmentWindow.setIconImage(null);
    TestEnvironmentWindow.setSize(new Dimension(1000, 650));

//  Content Section

    final TableModel dataModel = new AbstractTableModel() {

        public int getColumnCount(){ 
            return 5; 
        }

        public int getRowCount(){ 
            return 10;
        }

        public Object getValueAt(int row, int col){ 
            return new Integer(row*col); 
        }

        public boolean isCellEditable(int row, int col){
            return true; 
        }
    };

    JPanel Content = new JPanel();
    Content.setBounds(175, 0, 825, 605);
    TestEnvironmentWindow.getContentPane().add(Content);
    Content.setBackground(new Color(244,244,244));
    Content.setLayout(new CardLayout(0, 0));

    JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    Content.add(tabbedPane);
    JPanel set1Panel = new JPanel();
    set1Panel.setLayout(null);

    Vector<String> columnNames = new Vector<String>(2);
    columnNames.addElement("X-Values");
    columnNames.addElement("Y-Values");

    S1L1 = new JTable(data1, columnNames);
    S1L1.setFont(new Font("Work Sans", Font.PLAIN, 12));
    S1L1.setGridColor(new Color(150,150,150));
    JScrollPane S1L1Scroll = new JScrollPane(S1L1,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    S1L1Scroll.getVerticalScrollBar().setPreferredSize (new Dimension(0,0));
    dataModel1 = new DefaultTableModel(data1, columnNames);
    S1L1.setModel(dataModel1);
    S1L1Scroll.setBounds(38, 50, 225, 400);
    set1Panel.add(S1L1Scroll);

    S1L2 = new JTable(data2, columnNames);
    S1L2.setFont(new Font("Work Sans", Font.PLAIN, 12));
    S1L2.setGridColor(new Color(150,150,150));
    JScrollPane S1L2Scroll = new JScrollPane(S1L2,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    S1L2Scroll.getVerticalScrollBar().setPreferredSize (new Dimension(0,0));
    dataModel2 = new DefaultTableModel(data2, columnNames);
    S1L2.setModel(dataModel2);
    S1L2Scroll.setBounds(288, 50, 225, 400);
    set1Panel.add(S1L2Scroll);

    S1L3 = new JTable(data3, columnNames);
    S1L3.setFont(new Font("Work Sans", Font.PLAIN, 12));
    S1L3.setGridColor(new Color(150,150,150));
    JScrollPane S1L3Scroll = new JScrollPane(S1L3,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    S1L3Scroll.getVerticalScrollBar().setPreferredSize (new Dimension(0,0));
    dataModel3 = new DefaultTableModel(data3, columnNames);
    S1L3.setModel(dataModel3);
    S1L3Scroll.setBounds(538, 50, 225, 400);
    set1Panel.add(S1L3Scroll);

    JLabel ListOneLabel = new JLabel("List 1");
    ListOneLabel.setFont(new Font("Work Sans", Font.PLAIN, 16));
    ListOneLabel.setHorizontalAlignment(SwingConstants.CENTER);
    ListOneLabel.setBackground(new Color(220, 208, 192));
    ListOneLabel.setOpaque(true);
    ListOneLabel.setBounds(77, 20, 150, 20);
    set1Panel.add(ListOneLabel);

    JLabel ListTwoLabel = new JLabel("List 2");
    ListTwoLabel.setFont(new Font("Work Sans", Font.PLAIN, 16));
    ListTwoLabel.setHorizontalAlignment(SwingConstants.CENTER);
    ListTwoLabel.setBackground(new Color(220, 208, 192));
    ListTwoLabel.setOpaque(true);
    ListTwoLabel.setBounds(327, 20, 150, 20);
    set1Panel.add(ListTwoLabel);

    JLabel ListThreeLabel = new JLabel("List 3");
    ListThreeLabel.setFont(new Font("Work Sans", Font.PLAIN, 16));
    ListThreeLabel.setHorizontalAlignment(SwingConstants.CENTER);
    ListThreeLabel.setBackground(new Color(220, 208, 192));
    ListThreeLabel.setOpaque(true);
    ListThreeLabel.setBounds(577, 20, 150, 20);
    set1Panel.add(ListThreeLabel);

    JButton S1L1Reset = new JButton("Reset");
    S1L1Reset.setFont(new Font("Work Sans", Font.PLAIN, 14));
    S1L1Reset.setForeground(new Color(90, 90, 90));
    S1L1Reset.setBackground(new Color(220, 208, 192));
    S1L1Reset.setOpaque(true);
    S1L1Reset.setBorderPainted(false);
    S1L1Reset.setBorder(new RoundedBorder(20));
    S1L1Reset.setBounds(43, 465, 100, 20);
    set1Panel.add(S1L1Reset);
    S1L1Reset.addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
            S1L1Reset.setForeground(new Color(0,0,0));

        }
        public void mouseExited(MouseEvent e) {
            S1L1Reset.setForeground(new Color(90,90,90));
        }
    });
    S1L1Reset.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            deleteAllRows(dataModel1);
        }
    });
    S1L1Reset.setUI(new BasicButtonUI() {
        public void update(Graphics g, JComponent c) {
            if (c.isOpaque()) {
                Color fillColor = c.getBackground();
                g.setColor(fillColor);
                g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
            }
            paint(g, c);
        }
    });

    JButton S1L2Reset = new JButton("Reset");
    S1L2Reset.setFont(new Font("Work Sans", Font.PLAIN, 14));
    S1L2Reset.setForeground(new Color(90, 90, 90));
    S1L2Reset.setBackground(new Color(220, 208, 192));
    S1L2Reset.setOpaque(true);
    S1L2Reset.setBorderPainted(false);
    S1L2Reset.setBorder(new RoundedBorder(20));
    S1L2Reset.setBounds(293, 465, 100, 20);
    set1Panel.add(S1L2Reset);
    S1L2Reset.addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
            S1L2Reset.setForeground(new Color(0,0,0));
        }
        public void mouseExited(MouseEvent e) {
            S1L2Reset.setForeground(new Color(90,90,90));
        }
    });
    S1L2Reset.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            deleteAllRows(dataModel2);
        }
    }); 
    S1L2Reset.setUI(new BasicButtonUI() {
        public void update(Graphics g, JComponent c) {
            if (c.isOpaque()) {
                g.setColor(c.getBackground());
                g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
            }
            paint(g, c);
        }
    });

    JButton S1L3Reset = new JButton("Reset");
    S1L3Reset.setFont(new Font("Work Sans", Font.PLAIN, 14));
    S1L3Reset.setForeground(new Color(90, 90, 90));
    S1L3Reset.setBackground(new Color(220, 208, 192));
    S1L3Reset.setOpaque(true);
    S1L3Reset.setBorderPainted(false);
    S1L3Reset.setBorder(new RoundedBorder(20));
    S1L3Reset.setBounds(543, 465, 100, 20);
    set1Panel.add(S1L3Reset);
    S1L3Reset.addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
            S1L3Reset.setForeground(new Color(0,0,0));
        }
        public void mouseExited(MouseEvent e) {
            S1L3Reset.setForeground(new Color(90,90,90));
        }
    });
    S1L3Reset.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    }); 
    S1L3Reset.setUI(new BasicButtonUI() {
        public void update(Graphics g, JComponent c) {
            if (c.isOpaque()) {
                g.setColor(c.getBackground());
                g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
            }
            paint(g, c);
        }
    });

    JButton S1L1Save = new JButton("Save");
    S1L1Save.setFont(new Font("Work Sans", Font.PLAIN, 14));
    S1L1Save.setForeground(new Color(90, 90, 90));
    S1L1Save.setBackground(new Color(220, 208, 192));
    S1L1Save.setOpaque(true);
    S1L1Save.setBorderPainted(false);
    S1L1Save.setBorder(new RoundedBorder(20));
    S1L1Save.setBounds(155, 465, 100, 20);
    set1Panel.add(S1L1Save);
    S1L1Save.addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
            S1L1Save.setForeground(new Color(0,0,0));
        }
        public void mouseExited(MouseEvent e) {
            S1L1Save.setForeground(new Color(90,90,90));
        }
    });
    S1L1Save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    }); 
    S1L1Save.setUI(new BasicButtonUI() {
        public void update(Graphics g, JComponent c) {
            if (c.isOpaque()) {
                g.setColor(c.getBackground());
                g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
            }
            paint(g, c);
        }
    });

    JButton S1L2Save = new JButton("Save");
    S1L2Save.setFont(new Font("Work Sans", Font.PLAIN, 14));
    S1L2Save.setForeground(new Color(90, 90, 90));
    S1L2Save.setBackground(new Color(220, 208, 192));
    S1L2Save.setOpaque(true);
    S1L2Save.setBorderPainted(false);
    S1L2Save.setBorder(new RoundedBorder(20));
    S1L2Save.setBounds(405, 465, 100, 20);
    set1Panel.add(S1L2Save);
    S1L2Save.addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
            S1L2Save.setForeground(new Color(0,0,0));
        }
        public void mouseExited(MouseEvent e) {
            S1L2Save.setForeground(new Color(90,90,90));
        }
    });
    S1L2Save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    }); 
    S1L2Save.setUI(new BasicButtonUI() {
        public void update(Graphics g, JComponent c) {
            if (c.isOpaque()) {
                g.setColor(c.getBackground());
                g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
            }
            paint(g, c);
        }
    });

    JButton S1L3Save = new JButton("Save");
    S1L3Save.setFont(new Font("Work Sans", Font.PLAIN, 14));
    S1L3Save.setForeground(new Color(90, 90, 90));
    S1L3Save.setBackground(new Color(220, 208, 192));
    S1L3Save.setOpaque(true);
    S1L3Save.setBorderPainted(false);
    S1L3Save.setBorder(new RoundedBorder(20));
    S1L3Save.setBounds(655, 465, 100, 20);
    set1Panel.add(S1L3Save);
    S1L3Save.addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
            S1L3Save.setForeground(new Color(0,0,0));
        }
        public void mouseExited(MouseEvent e) {
            S1L3Save.setForeground(new Color(90,90,90));
        }
    });
    S1L3Save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    });     
    S1L3Save.setUI(new BasicButtonUI() {
        public void update(Graphics g, JComponent c) {
            if (c.isOpaque()) {
                g.setColor(c.getBackground());
                g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
            }
            paint(g, c);
        }
    });

    JButton ClearAll = new JButton("Clear All");
    ClearAll.setFont(new Font("Work Sans", Font.PLAIN, 14));
    ClearAll.setForeground(new Color(90, 90, 90));
    ClearAll.setBackground(new Color(220, 208, 192));
    ClearAll.setOpaque(true);
    ClearAll.setBorderPainted(false);
    ClearAll.setBorder(new RoundedBorder(20));
    ClearAll.setBounds(238, 515, 150, 25);
    set1Panel.add(ClearAll);
    ClearAll.addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
            ClearAll.setForeground(new Color(0,0,0));
        }
        public void mouseExited(MouseEvent e) {
            ClearAll.setForeground(new Color(90,90,90));
        }
    });
    ClearAll.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    }); 
    ClearAll.setUI(new BasicButtonUI() {
        public void update(Graphics g, JComponent c) {
            if (c.isOpaque()) {
                g.setColor(c.getBackground());
                g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
            }
            paint(g, c);
        }
    });

    JButton SaveAll = new JButton("Save All");
    SaveAll.setFont(new Font("Work Sans", Font.PLAIN, 14));
    SaveAll.setForeground(new Color(90, 90, 90));
    SaveAll.setBackground(new Color(220, 208, 192));
    SaveAll.setOpaque(true);
    SaveAll.setBorderPainted(false);
    SaveAll.setBorder(new RoundedBorder(20));
    SaveAll.setBounds(410, 515, 150, 25);
    set1Panel.add(SaveAll);
    SaveAll.addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
            SaveAll.setForeground(new Color(0,0,0));
        }
        public void mouseExited(MouseEvent e) {
            SaveAll.setForeground(new Color(90,90,90));
        }
    });
    SaveAll.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    }); 
    SaveAll.setUI(new BasicButtonUI() {
        public void update(Graphics g, JComponent c) {
            if (c.isOpaque()) {
                g.setColor(c.getBackground());
                g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
            }
            paint(g, c);
        }
    });

    tabbedPane.add(set1Panel);

//  Menu Bar Section
    JPanel MenuBar = new JPanel();
    MenuBar.setBackground(new Color(220, 208, 192));
    MenuBar.setBounds(0, 0, 175, 605);
    TestEnvironmentWindow.getContentPane().add(MenuBar);
    MenuBar.setLayout(null);

//  Menu Bar Section    
    JMenuBar menuBar = new JMenuBar();
    TestEnvironmentWindow.setJMenuBar(menuBar);

    JMenu mnFile = new JMenu("File");
    menuBar.add(mnFile);

    JMenu mnEdit = new JMenu("Edit");
    menuBar.add(mnEdit);

    JMenu mnSearch = new JMenu("Search");
    menuBar.add(mnSearch);

    JMenu mnWindow = new JMenu("Window");
    menuBar.add(mnWindow);

    JMenu mnHelp = new JMenu("Help");
    menuBar.add(mnHelp);
}

public static void deleteAllRows(final DefaultTableModel model) {
    for( int i = model.getRowCount() - 1; i >= 0; i-- ) {
        model.removeRow(i);
    }
}
}

2 个答案:

答案 0 :(得分:2)

swing组件使用UI委托绘制自己,背景绘画在基类ComponentUI中完成,如下所示:

public void update(Graphics g, JComponent c) {
    if (c.isOpaque()) {
        g.setColor(c.getBackground());
        g.fillRect(0, 0, c.getWidth(),c.getHeight());
    }
    paint(g, c);
}

如您所见,它使用fillRect,因此必须以矩形方式填充背景。要更改它,请创建BasicButtonUI的子类(其子类是各种外观和感觉的UI委托),并通过填充圆形rect来覆盖此方法:

    S1L1Reset.setUI(new BasicButtonUI() {
        @Override
        public void update(Graphics g, JComponent c) {
            if (c.isOpaque()) {
                Color fillColor = c.getBackground();

                AbstractButton button = (AbstractButton) c;
                ButtonModel model = button.getModel();

                if (model.isPressed()) {
                    fillColor = fillColor.darker();
                } else if (model.isRollover()) {
                    fillColor = fillColor.brighter();
                }

                g.setColor(fillColor);
                g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
            }
            paint(g, c);
        }
    });

正如您在代码中看到的,您需要处理按钮的各种状态,如鼠标按下背景,因为这些是在BasicButtonUI子类中完成的,因为您不再使用这些子类,所以您必须实现所有这是你自己。您可以参考MetalButtonUI,以获取一个按钮如何在Metal外观和放大器中的不同状态下自我绘制的示例。感觉。

也许不需要调用setBorderPainted(false)?如果你真的想要利用圆形边框,你应该需要它来画画。

The round button in action!

答案 1 :(得分:0)

只需使用setRoundRect(double a, double y, double w, double h, double arcWidth, double arcHeight)的方法来调整RoundButton类的宽度和高度以及拐角即可。

RoundButton类扩展了JButton {

    public RoundButton(String label) {
        super(label);
        Dimension size = getPreferredSize();
        size.width = size.height = Math.max(size.width,size.height);
        setPreferredSize(size);

        setContentAreaFilled(false);
    }

    protected void paintComponent(Graphics g) {
        if (getModel().isArmed()) {
            g.setColor(Color.lightGray);
        } else {
            g.setColor(getBackground());
        }
        g.fillRoundRect(0, 0, 250, 50, 40, 40);
        super.paintComponent(g);
    }

    protected void paintBorder(Graphics g) {
        g.setColor(getForeground());
        g.drawRoundRect(0, 0, 250, 50, 10, 10); 
    }

    Shape shape;
    public boolean contains(int x, int y) {
        if (shape == null || 
                !shape.getBounds().equals(getBounds())) {
            shape = new RoundRectangle2D.Float(0, 0, 250, 50,10,10);
        }
        return shape.contains(x, y);
    }

}

要使用该类,例如

JButton a = new RoundButton("ABC");
a.setBounds(400,0,250,50);
a.setForeground(Color.WHITE);
a.setBackground(Color.BLACK);
a.setFont(new Font("Roboto", Font.BOLD, 15));
panel.add(a);