求大神帮个忙,为什么长方形没有显示在GUI里?哪里出错了?
public class SelectSeat {
static JFrame frame;
public JPanel createContentPane() throws IOException
{
JPanel totalGUI = new JPanel();
RectDraw rect= new RectDraw();
rect.setPreferredSize(new Dimension(30,25));
totalGUI.setLayout(null);
totalGUI.setBackground(Color.WHITE);
totalGUI.add(rect);
return totalGUI;
}
void setVisible(boolean b) {
// TODO Auto-generated method stub
}
static void createAndShowGUI() throws IOException
{
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("Seat Selection");
//Create and set up the content pane.
SelectSeat demo = new SelectSeat();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(535, 520);
frame.setLocation(500,220);
frame.setVisible(true);
}
private static class RectDraw extends JPanel
{
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(29,550,300,250);
g.setColor(Color.GRAY);
g.fillRect(20,5,330,25);
g.setColor(Color.BLUE);
g.drawString("Movie Sceen", 150, 20);
}
}
}
原因是
totalGUI.setLayout(null);
導致的問題,我一開始也覺得很奇怪後來我參考了這個問題 http://stackoverflow.com/questions/12308764/java-setlayoutnull
解決方法,一個是不用
setLayout(null);
,改用佈局管理器或是上面問題中一個回答的思路為你要展示的對象添加bound 防止顯示的範圍肉眼不可見