日期:2014-05-20 浏览次数:20875 次
try{UIManager.setLookAndFeel(
"com.sun.java.seing.plaf.motif.MotifLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
}catch(Exception e){
e.printStackTrace();
}
------解决方案--------------------
楼主的这种画图的做法本身就很不可取
去强行获得一个指定的 JPanel 的 Graphics 对象,然后让这个 Graphics 去绘制?
这个方法你是怎么想出来的?
JPanel 的绘制不知你这样做的
每个控件都有两个很重要的绘制方法
paint 和 paintComponent
你想绘制一个控件的话,应当重写这两个方法中的某一个
建议重写 paintComponent 方法
为什么呢?
因为,每当你的控件发生需要绘制的事件的时候(比如大小变化、第一次显示等等)
Swing 会自动调用 repaint 方法,
从而又调用到 paint 和 paintComponent 方法
如果你不重写 paint 和 paintComponent 方法
只是单纯的把 Graphics 对象强行拿出来让其绘制,很容易就会让你绘制的东西丢失
不信当你的图画出来后,你把窗体的大小改变一下,看看画的东西还在
把楼主的程序改了一下,楼主看看吧
效果是,点一下按钮进行绘制,再点一下取消绘制
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class L0101 extends BaseFrame {
JButton btnDraw;
JPanel pnlScreen;
boolean needPaint;
//===============================
public static void main(String args[]) {
L0101 myAppli = new L0101("Let's Get Grahpics !");
myAppli.setSize(300, 300);
myAppli.setVisible(true);
}
//===============================
public L0101(String title) {
super("Let's Get Grahpics !");
btnDraw = new JButton("画图");
pnlScreen = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (needPaint) {
int j = 0;
for (int i = 10; i <= 100; i = i + 5) {
g.setColor(new Color(j, j, j));
g.drawOval(i, i, i + 10, i + 10);
j += 12;
}
}
}
};
//按钮事件
btnDraw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
needPaint = !needPaint;
pnlScreen.repaint();
}
});
getContentPane().add(btnDraw, BorderLayout.NORTH);
getContentPane().add(pnlScreen, BorderLayout.CENTER);
}
}