简体   繁体   English

直到MouseOver,JButton才会出现

[英]JButtons do not appear until MouseOver

I'm trying to get JButtons which have been added to a JPanel to show up during the execution of a program, however they only appear when I hover the mouse of them, they remain invisible until then. 我正在尝试将已添加到JPanel中的JButton显示在程序执行期间,但是只有当我将鼠标悬停在它们上面时它们才会出现,直到那时它们仍然不可见。

Below is my code, I've tried repaint() and revalidate() with no luck. 下面是我的代码,我尝试了repaint()和revalidate()没有运气。

There also seems to be an issue with the height of the JPanel, it seems to be larger than the main Window for some reason JPanel的高度似乎也存在问题,由于某种原因它似乎比主窗口大

import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;


public final class SideMenu extends JPanel implements ActionListener{
    private final int width;
    private final int height;

    public SideMenu(int width, int height){        
        this.width = width;
        this.height = height;
        this.setLayout(new GridLayout(0,1));
        this.add(new JButton("button1"));
        this.add(new JButton("button2"));
        this.add(new JButton("button3"));
        this.revalidate();
        this.repaint(); 
    }

    @Override
    public void paint(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.black);
        g.fillRect(0, 0, width, height);
    }


    @Override
    public void actionPerformed(ActionEvent e) {        
        repaint();  
    }

    public static void main(String[] args){
        int width = 300, height = 400;

        JFrame jf = new JFrame();
        jf.setTitle("Fish Tank");
        jf.setSize(width, height);
        jf.setVisible(true);
        jf.setLayout(null);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ///jf.setResizable(false);

        SideMenu side_menu = new SideMenu(100,height);        
        jf.add(side_menu);
        side_menu.setBounds(200, 0, 100, height);
    }
}

Use paintComponent(..) method instead of paint(..) : 使用paintComponent(..)方法而不是paint(..)

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.black);
    g.fillRect(0, 0, width, height);
}

Read more about custom paintings . 阅读更多关于定制画作

Also call jf.setVisible(true); 也调用jf.setVisible(true); at the end of construction of GUI, when you add all components to JFrame . 在构建GUI时,将所有组件添加到JFrame

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

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