简体   繁体   English

使JButton可单击而不是JLabel

[英]Make JButton clickable instead of JLabel

I have a case where I put the JLabel inside JButton and adapts the JButton size. 我有一种情况,我将JLabel放在JButton内并调整JButton的大小。

The issue here is everytime I click the button, the JLabel catches most of the events. 这里的问题是,每当我单击按钮时,JLabel都会捕获大多数事件。

When I tried to add ActionListener to the JButton, it didn't work. 当我尝试将ActionListener添加到JButton时,它没有起作用。

But when I tried to add MouseListener to JLabel, all the event handlers work. 但是,当我尝试将MouseListener添加到JLabel时,所有事件处理程序都可以工作。

I want the ActionListener for the JButton to work. 我希望JButton的ActionListener能够工作。 I don't want the JLabel to catches all of the events without destroying my default configuration on them. 我不希望JLabel在不破坏其默认配置的情况下捕获所有事件。

I tried setting the JLabel focusable property to false but it didn't work also. 我尝试将JLabel focusable属性设置为false,但是它也不起作用。

So what should I do then? 那我该怎么办呢?

I have a case where I put the JLabel inside JButton and adapts the JButton size. 我有一种情况,我将JLabel放在JButton内并调整JButton的大小。

this is basic property, by default top layed JComponent consume all events came from Mouse & Keyboard 这是基本属性,默认情况下,最上层的JComponent使用所有来自MouseKeyboard事件

there are two ways 有两种方法

  • (no idea why is there JLabel ) if is possible to use plain JButton with implemented methods in API instead (不知道为什么会有JLabel )是否可以将纯JButton与API中的已实现方法一起使用

  • add MouseListener (maybe there no reason to override all MouseEvents add only MouseAdapter ) to JLabel and from mouseClicked to call JButton.doClick() MouseListener添加到JLabel (可能没有理由重写所有MouseEvents仅添加MouseAdapter ),然后从mouseClicked中调用JButton.doClick()

EDIT 编辑

@Mad, @狂,

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.swing.*;

public class JButtonAndIcon {

    private JLabel label = new JLabel();
    private Random random = new Random();
    private ImageIcon image1; // returns null don't worry about in Swing
    private ImageIcon image2; // returns null don't worry about in Swing
    private Timer backTtimer;
    private int HEIGHT = 300, WEIGHT = 200;


    public JButtonAndIcon() {
        label.setPreferredSize(new Dimension(HEIGHT, WEIGHT));
        final JButton button = new JButton("Push");
        button.setBorderPainted(false);
        button.setBorder(null);
        button.setFocusable(false);
        button.setMargin(new Insets(0, 0, 0, 0));
        button.setContentAreaFilled(false);
        button.setLayout(new BorderLayout());
        button.add(label);
        button.setMultiClickThreshhold(1000);
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (button.getIcon() == image1) {
                    label.setIcon(image2);
                } else {
                    label.setIcon(image1);
                    if(backTtimer.isRunning()){
                         backTtimer.restart();
                    }                   
                }
            }
        });
        JFrame frame = new JFrame("Test");
        frame.add(button);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        startBackground();
        frame.setVisible(true);
    }

    public static void main(String[] args) throws IOException {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JButtonAndIcon t = new JButtonAndIcon();
            }
        });
    }

    private void startBackground() {
        backTtimer = new javax.swing.Timer(1500, updateBackground());
        backTtimer.start();
        backTtimer.setRepeats(true);
    }

    private Action updateBackground() {
        return new AbstractAction("Background action") {

            private final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                label.setIcon(new ImageIcon(getImage()));
            }
        };
    }

    public BufferedImage getImage() {
        int w = label.getWidth();
        int h = label.getHeight();
        GradientPaint gp = new GradientPaint(0f, 0f, new Color(
                127 + random.nextInt(128),
                127 + random.nextInt(128),
                127 + random.nextInt(128)),
                w, w,
                new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bi.createGraphics();
        g2d.setPaint(gp);
        g2d.fillRect(0, 0, w, h);
        g2d.setColor(Color.BLACK);
        return bi;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM