当实例化我修改的JPanel
类时,我通过构造函数传入一个文件。文件(XML)被读取,稍后在paint
方法中我将使用该数据。但是,在解析数据后,我同时调用了repaint()
和revalidate()
,但我的GUI看起来完全一样。我将这些方法称为JFrame
的主类和JPanel
的面板类。为什么我的JFrame不像我告诉的那样重新绘制?
当我选择从我JFileChooser
一个XML文件中,drawPanel
类获取与它的其它构造函数实例,同时在文件中,并解析它,然后调用repaint
和revalidate
。我省略了大部分代码以节省您的时间。
这里的主类的代码:
public class myCode extends JFrame {
public myCode() {
super("Roadway Simulator");
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
drawie = new drawPanel();
drawie.setSize(new Dimension(width - 200, height));
drawie.setMinimumSize(new Dimension(width - 200, height));
drawie.setMaximumSize(new Dimension(width - 200, height));
drawie.setLocation(0, 0);
add(drawie);
setVisible(true);
try{Thread.sleep(500);revalidate();repaint();}catch(InterruptedException eeee){}
}
public static void main(String[] args){new myCode();}
}
这里是我的drawPanel类:
class drawPanel extends JPanel {
boolean drawRoad = false;
public drawPanel() {
super();
}
public drawPanel(Document doc){
super();
//the change in my paint method
drawRoad = true;
revalidate();
repaint();
}
public paint(Graphics g){
super.paint(g);
if(drawRoad){
g.setColor(Color.BLACK);
g.fillRect(0,0,600,600);
}
}
}
我的代码是上面一样,只是多了很多细节。为什么不是我的JFrame重新绘制?
避免使用'null'布局,像素完美的布局是现代UI设计中的幻想。影响组件的个体大小的因素太多,其中没有一个可以控制。 Swing旨在与布局经理一起工作,放弃这些将导致问题和问题的终结,您将花费越来越多的时间来尝试纠正 – MadProgrammer 2014-10-22 01:23:12
[我是否应避免使用set(Preferred | Maximum | Minimum)在Java Swing中的大小方法?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) - 但在你的情况,因为你''使用'null'布局,它们将无效...... – MadProgrammer 2014-10-22 01:23:42