How to use a JPanel as JButton?

泪湿孤枕 提交于 2021-02-19 08:41:27

问题


I must use a swing-ui designer tool to create my UI, that only supports graphically editing JPanels. Those panels (they basically contain complex button designs) to work like a JButton. I cannot use anything other than JPanel as base class of these panels (UI editor limitation).

What is the most generic solution to do this?

  • Create a custom button that uses the panel's draw method instead of it's own?
  • Create a base-panel class that reimplements the whole button?
  • Another more elegant solution?

回答1:


Here is a quick demo, to show you how you could use borders to simulate a button.

The demo also reacts to mouse and key events :

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;

public class JPanelButton extends JPanel {

    Border raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
    Border loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);

    public static void main(final String[] args) {

        JFrame frame = new JFrame();

        final JPanelButton panel = new JPanelButton();
        panel.raiseBorder();

        panel.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(final MouseEvent e) {
                panel.lowerBorder();

            }

            @Override
            public void mouseReleased(final MouseEvent e) {
                panel.raiseBorder();

            }

        });

        panel.setFocusable(true); // you need this or the panel won't get the key events
        panel.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(final KeyEvent e) {
                panel.lowerBorder();

            }

            @Override
            public void keyReleased(final KeyEvent e) {
                panel.raiseBorder();

            }
        });

        frame.setContentPane(panel);
        frame.setSize(100, 100);
        frame.setVisible(true);

    }

    public void raiseBorder() {

        setBorder(raisedetched);
    }

    public void lowerBorder() {

        setBorder(loweredetched);
    }

}



回答2:


Simply add MouseListener.

JPanel jp = new JPanel();
jp.addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent e) {
        System.out.println("Clicked");
    }

});

If this answer isn't specific enough, leave a comment and I'll give you more explanation.



来源:https://stackoverflow.com/questions/39955390/how-to-use-a-jpanel-as-jbutton

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!