ad是我写的一个JPanel的子类: class ad extends JPanel { public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Line2D.Double Line=new Line2D.Double(10,10,80,40);
g2.setPaint(Color.BLACK);
g2.draw(Line);
}
}
public test()
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame f = new JFrame("draw Line");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ad a=new ad();
a.setPreferredSize(new Dimension(150,100));
a.setBackground(Color.blue);//这句没有作用
f.getContentPane().add(a);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new test();
}
但是改成
public test()
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame f = new JFrame("draw Line");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel a=new JPanel();
a.setPreferredSize(new Dimension(150,100));
a.setBackground(Color.blue);//这句就有用了
f.getContentPane().add(a);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new test();
}
这是为什么呀?
ad不是继承的JPanel类么,setBackground(...)方法应该可以用的~为什么会出现这样的情况呀?
{
Graphics2D g2 = (Graphics2D)g;
Line2D.Double Line=new Line2D.Double(10,10,80,40);
g2.setPaint(Color.BLACK);
g2.draw(Line);
}
}
public test()
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame f = new JFrame("draw Line");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ad a=new ad();
a.setPreferredSize(new Dimension(150,100));
a.setBackground(Color.blue);//这句没有作用
f.getContentPane().add(a);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new test();
}
但是改成
public test()
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame f = new JFrame("draw Line");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel a=new JPanel();
a.setPreferredSize(new Dimension(150,100));
a.setBackground(Color.blue);//这句就有用了
f.getContentPane().add(a);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new test();
}
这是为什么呀?
ad不是继承的JPanel类么,setBackground(...)方法应该可以用的~为什么会出现这样的情况呀?
而你直接实例化JPanel类,这个类里面本来就有setBackground方法,当然就可以引用了。
不矛盾吧,楼主应该再看一下面向对象!
super.paint(g); // 这样子就又行了
Graphics2D g2 = (Graphics2D)g;
Line2D.Double Line=new Line2D.Double(10,10,80,40);
g2.setPaint(Color.BLACK);
g2.draw(Line);
}
paintComponent方法却不行呢?(覆盖的方法里调用了super.Background())