Как создать кнопку поля со списком - PullRequest
0 голосов
/ 04 августа 2020

Этот компонент существует в Java? Это кнопка с прикрепленным полем со списком. введите описание изображения здесь

1 Ответ

0 голосов
/ 05 августа 2020

У меня есть аналогичный компонент, который я разработал в одном из моих собственных проектов. При необходимости замените все пользовательские компоненты (например, CToolBarButton на JButton, CPanel на JPanel, CButton на JButton). Вы также можете использовать классы пользовательского интерфейса настройки для получения желаемого внешнего вида.

package com.custom.ui.base.control;

import com.custom.ui.base.border.ToolbarButtonOptionsBorder;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

/**
 * This is Options button in for ToolBar. This Toolbar button can contain other toolbar buttons those
 * would be displayed in the popup
 *
 * @version 1.0.0.1 (Jul 29, 2010)
 * @author Arindam Roy
 */
public class CToolbarButtonOptions extends CToolBarButton implements ActionListener, PopupMenuListener {

    /**
     * Holds number of buttons in the Popup
     */
    int count = 0;

    /**
     * Holds the Columns in the popup
     */
    private int maxColumnCount = 3;

    /**
     * Creates new form BeanForm
     */
    public CToolbarButtonOptions() {
        initComponents();
        init();
    }

    /**
     * Initializes additional components in this screen
     */
    private void init() {
        jPopupMenu.add(dmPanel);
        setListeners();
    }

    /**
     * Adds listeners to the components
     */
    private void setListeners() {
        this.addActionListener(this);
        this.jPopupMenu.addPopupMenuListener(this);
    }

    /**
     * Adds a Toolbar button in the popup
     *
     * @param toolBarButton <code>CToolBarButton</code> instance to add in the popup
     * @see CToolBarButton
     * @see #remove(com.dbm.base.control.DMToolBarButton)
     */
    public void add(CToolBarButton toolBarButton) {
        dmPanel.add(toolBarButton);
        toolBarButton.addActionListener(this);
        count++;
        updateLayout();
    }

    /**
     * Returns components of Option button popup menu
     *
     * @return <code>Component[]</code> that contains components of popup menu
     */
    public Component[] getPopupComponents() {
        return dmPanel.getComponents();
    }

    /**
     * Removes a Toolbar button from the popup
     *
     * @param toolBarButton <code>CToolBarButton</code> instance to remove from the popup
     * @see CToolBarButton
     * @see #add(com.dbm.base.control.DMToolBarButton)
     */
    public void remove(CToolBarButton toolBarButton) {
        toolBarButton.removeActionListener(this);
        count--;
        dmPanel.remove(toolBarButton);
    }

    /**
     * Recognize the columns and rows to place popup menu buttons in the Popup
     */
    private void updateLayout() {
        if (dmPanel.getLayout() instanceof GridLayout) {
            int row = (count / getMaxColumnCount());
            if (count % getMaxColumnCount() > 0) {
                row++;
            }
            int column = count >= maxColumnCount ? maxColumnCount : count;
            if (!(row == 0 && column == 0)) {
                ((GridLayout) dmPanel.getLayout()).setRows(row);
                ((GridLayout) dmPanel.getLayout()).setColumns(column);
            }
        }
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu = new javax.swing.JPopupMenu();
        dmPanel = new com.custom.ui.base.container.CPanel();

        jPopupMenu.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(38, 144, 72)), javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255))));

        dmPanel.setLayout(new java.awt.GridLayout(1, 1, 0, 1));

        setBorder(new ToolbarButtonOptionsBorder());
        setPreferredSize(new java.awt.Dimension(25, 8));
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Action Handler for Action Events
     *
     * @param e <code>ActionEvent</code> instance that holds the event details
     */
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == this) {
            jPopupMenu.show(this, 2, this.getBounds().y + this.getBounds().height + 1);
        } else {
            jPopupMenu.setVisible(false);
        }
    }

    /**
     * Returns the number of columns, according to that the Popup menu buttons are placed
     *
     * @return <code>int</code> column count in the popup menu for button placement
     * @see #setMaxColumnCount(int)
     */
    public int getMaxColumnCount() {
        return maxColumnCount;
    }

    /**
     * Sets the number of columns, according to that the Popup menu buttons are placed
     *
     * @param maxColumnCount <code>int</code> column count in the popup menu for button
     * placement, to set
     * @see #getMaxColumnCount()
     */
    public void setMaxColumnCount(int maxColumnCount) {
        this.maxColumnCount = maxColumnCount;
        updateLayout();
    }

    /**
     * Action handler for Popup menu listener. This method handles the event of "popup menu visible"
     *
     * @param e <code>PopupMenuEvent</code> instance that holds the event details
     */
    public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
        this.getModel().setRollover(true);
    }

    /**
     * Action handler for Popup menu listener. This method handles the event of "popup menu visible"
     *
     * @param e <code>PopupMenuEvent</code> instance that holds the event details
     */
    public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
        this.getModel().setRollover(false);
    }

    /**
     * Action handler for Popup menu listener. This method handles the event of "popup menu visible"
     *
     * @param e <code>PopupMenuEvent</code> instance that holds the event details
     */
    public void popupMenuCanceled(PopupMenuEvent e) {
        this.getModel().setRollover(false);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.custom.ui.base.container.CPanel dmPanel;
    private javax.swing.JPopupMenu jPopupMenu;
    // End of variables declaration//GEN-END:variables
}

Это будет выглядеть так: этот

Пользовательский класс границы:

package com.custom.ui.base.border;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.border.EmptyBorder;

/**
 * This border for toolbar button component holds group of buttons. Clicking on this, one popup comes that
 * contains all the options buttons available against this toolbar button.
 *
 * @version 1.0.0.1 (Sep 15, 2010)
 * @author Arindam Roy
 */
public class ToolbarButtonOptionsBorder extends EmptyBorder {

    /**
     * Indicates width of the Down arrow icon width
     */
    private int optionArrowWidth = 7;

    /**
     * Creates new instance of ToolbarButtonOptionsBorder
     */
    public ToolbarButtonOptionsBorder() {
        super(new Insets(4, 4, 4, 8));
    }

    /**
     * Paints the border for the specified component with the specified position and size.
     *
     * @param c the component for which this border is being painted
     * @param g the paint graphics
     * @param x the x position of the painted border
     * @param y the y position of the painted border
     * @param width the width of the painted border
     * @param height the height of the painted border
     */
    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        super.paintBorder(c, g, x, y, width, height);
        g.setColor(Color.LIGHT_GRAY);
        int xPoints[] = new int[]{x + width - optionArrowWidth - 1, x + width - 1, x + width - 2 - (optionArrowWidth / 2)};
        int yPoints[] = new int[]{y + (height / 2) - 1, y + (height / 2) - 1, y + (height / 2) + 3};
        g.fillPolygon(xPoints, yPoints, xPoints.length);

        g.drawLine(x + width - optionArrowWidth - 2, y + 5, x + width - optionArrowWidth - 2, height - 3);

        g.setColor(Color.BLACK);
        xPoints = new int[]{x + width - optionArrowWidth, x + width - 2, x + width - 2 - (optionArrowWidth / 2)};
        yPoints = new int[]{y + (height / 2) - 1, y + (height / 2) - 1, y + (height / 2) + 2};
        g.fillPolygon(xPoints, yPoints, xPoints.length);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...