java - JPanel 中的 JButtons 仅在鼠标悬停时出现

标签 java swing jpanel jbutton mouseover

这是我的 JFrame 类,它创建并包含 JPanel,而 JPanel 又包含按钮。

import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Window extends JFrame{
    private static final long serialVersionUID = 1L;

    private Grid grid;
    private SquareButton[][] buttons;
    private JPanel board;

    public Window(){
        super("Territories");

        grid=new Grid();
        buttons=new SquareButton[8][8];
        board=new JPanel(new GridLayout(8, 8));

        //Creates each button with proper x and y values and adds each to the board
        for (int i=0; i<8; i++){
            for (int j=0; j<8; j++){
                buttons[j][i]=new SquareButton(j, i);
                board.add(buttons[j][i]);
            }
        }

        //Setting some frame properties
        setSize(560, 560);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        board.setVisible(true);
        add(board);

        setVisible(true);

    }
}

这是我的 JButton 类。

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.JButton;

public class SquareButton extends JButton{
    private static final long serialVersionUID = 1L;

    private int x, y;

    public SquareButton(int x, int y){
        super();

        this.x=x;
        this.y=y;

        setPreferredSize(new Dimension(70, 70));
        setBorder(BorderFactory.createBevelBorder(0, Color.white, new Color(216, 216, 216)));
        setBackground(new Color(247, 247, 247));

        setVisible(true);
    }

    public int getX(){
        return x;
    }

    public int getY(){
        return y;
    }
}

最佳答案

这与您拥有用于自定义按钮的方法 getX()getY() 这一事实有关。每个 JComponent(包括子类 JButton)都有一个 getX and getY already .因此,当在 SquareButton 中定义您自己的方法时,您最终会覆盖用于定位的原始方法。我不确定方法调用的顺序,但布局管理器使用这些方法来确定组件的布局。

如果您不需要这些方法,只需删除它们,或者更改名称即可。

旁白:您不需要对所有组件调用 setVisible。在框架上调用它就足够了。也并不是说您实际上没有向按钮添加任何特殊功能(至少从您所展示的内容来看),因此它可能比创建 JButton 的实例并设置其属性更可取,而不是创建自定义按钮类。

关于java - JPanel 中的 JButtons 仅在鼠标悬停时出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25353421/

相关文章:

Java 不会在不包含 main 的不同类中打印

java - RxJava onErrorResumeNext 调度器

java - 禁用或拦截窗外的掉落

java - JPanel 和 java g.fillOval() 方法发生了一些奇怪的事情

java - 从 JPanel 中完全删除 JLabel ...未设置可见(假)

java如何获取完整的堆栈信息

java - JUnit 5 : Is it possible to set a TestExecutionListener in Maven Surefire Plugin?

java - JOptionPane 会降低应用程序性能吗?

Java,JTextField .equals

java - 使用cardLayout时JPanel不会显示paintComponent