1
我試圖讓JButtons被添加到一個JPanel中以顯示在程序執行過程中,但是隻有當我將鼠標懸停在它們上方時纔會出現,直到那時它們纔會隱藏。JButtons不會出現,直到MouseOver
下面是我的代碼,我試過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);
}
}
'jf.setVisible(true);'應該是'main'方法中的最後一個語句。 – Tom 2014-11-05 15:11:06