我试图让已添加到 JPanel 的 JButtons 在程序执行期间显示,但是它们仅在我将鼠标悬停在它们上面时才出现,在此之前它们保持不可见。
下面是我的代码,我尝试了 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);
}
}
最佳答案
使用paintComponent(..)
方法而不是paint(..)
:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.fillRect(0, 0, width, height);
}
了解更多关于custom paintings的信息.
当您将所有组件添加到 JFrame
时,还要在 GUI 构建结束时调用 jf.setVisible(true);
。
关于java - JButtons 在 MouseOver 之前不会出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26760367/