java - 为什么长方形没有显示在GUI里?
本文介绍了java - 为什么长方形没有显示在GUI里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
求大神帮个忙,为什么长方形没有显示在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 防止显示的范围肉眼不可见
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);
Dimension d = rect.getPreferredSize();
rect.setBounds(10, 20, d.width, d.height);
return totalGUI;
}
这篇关于java - 为什么长方形没有显示在GUI里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文