我写的继承自JComponent的类,功能简单,打印“Hello World”
public class MyCanvas extends JComponent {
@Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.RED);
g2d.drawString("hello world", 60, 60);
}
}主函数,将我编写的小组件添加到JFrame上,并设置其背景色,无效。
public class MyFrame extends JFrame { private JPanel contentPane; public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame frame = new MyFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} public MyFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(300, 300, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
MyCanvas myCanvas = new MyCanvas();
myCanvas.setOpaque(true);
myCanvas.setBackground(Color.YELLOW);//设置背景色,无效
contentPane.add(myCanvas, BorderLayout.CENTER);
setContentPane(contentPane);
}}如何才能让我的类中的setBackground方法可以使用呢?该如何编写代码呢?
public class MyCanvas extends JComponent {
@Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.RED);
g2d.drawString("hello world", 60, 60);
}
}主函数,将我编写的小组件添加到JFrame上,并设置其背景色,无效。
public class MyFrame extends JFrame { private JPanel contentPane; public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame frame = new MyFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} public MyFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(300, 300, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
MyCanvas myCanvas = new MyCanvas();
myCanvas.setOpaque(true);
myCanvas.setBackground(Color.YELLOW);//设置背景色,无效
contentPane.add(myCanvas, BorderLayout.CENTER);
setContentPane(contentPane);
}}如何才能让我的类中的setBackground方法可以使用呢?该如何编写代码呢?
public void setBackground(Color bg)设置此组件的背景色。背景色仅在组件是不透明时才使用,并且只能由 JComponent 或 ComponentUI 实现的子类使用。JComponent 的直接子类必须重写 paintComponent 以遵守此属性。
由外观决定是否遵守此属性,某些外观可以选择忽略它。就是说,你必须在你的实现类里,使用此背景色来填充,缺省情况下JComponent似乎不会帮你做