直到MouseOver,JButton才会出现

时间:2014-11-05 15:04:15

标签: java swing jpanel jbutton

我试图将已添加到JPanel中的JButton显示在程序执行期间,但是只有当我将鼠标悬停在它们上面时它们才会出现,直到那时它们仍然不可见。

下面是我的代码,我已经尝试过repaint()和revalidate()而没有运气。

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);
    }
}

1 个答案:

答案 0 :(得分:3)

使用paintComponent(..)方法代替paint(..)

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

详细了解custom paintings

当您将所有组件添加到jf.setVisible(true);时,也会在构建GUI时调用JFrame