我使用以下代码显示两个字符串,我直接在jfame上绘制它们而不是将它们添加为组件或jpanel.But为什么我得到一个空白窗口而不是获取字符串。我错了?
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SimpleAttributes extends JFrame{
SimpleAttributes()
{
super("Simple Attributes");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
//setUndecorated(true);
Container cp=this.getContentPane();
cp.setBackground(new Color(0,200,0,0));
setVisible(true);
}
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D)g.create();
g2.setColor(Color.RED);
g2.drawString("One", 10, 10);
g.drawString("Two", 10,40);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable(){public void run(){new SimpleAttributes();}});
}
}
答案 0 :(得分:4)
JFrame不是一个组件,因此没有paintComponent()
函数。 See the API documentation
答案 1 :(得分:2)
如上所述,上述情况不正确,没有这样的方法,(我打算快速打字)并考虑JPanels。
您可以创建自己的Container
并覆盖paint()
方法,然后将ContentPane
用作frame.setContentPane(Container con)
:
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SimpleAttributes extends JFrame {
SimpleAttributes() {
super("Simple Attributes");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
//setUndecorated(true);
setContentPane(new MyContainer());
getContentPane().setBackground(new Color(0, 200, 0, 0));
setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleAttributes();
}
});
}
}
class MyContainer extends Container {
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(Color.RED);
g2.drawString("One", 10, 10);
g.drawString("Two", 10, 40);
}
}
如对一个答案的评论中所述,您可以使用paint()
的{{1}}来补偿对话框标题的偏移量:
JFrame
但是所有这些只会让你更加头疼,为什么不把它作为首选方式呢? import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SimpleAttributes extends JFrame {
SimpleAttributes() {
super("Simple Attributes");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
//setUndecorated(true);
getContentPane().setBackground(new Color(0, 200, 0, 0));
setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(Color.RED);
g2.drawString("One", 10, 10);//wont show
g2.drawString("One", 50, 50);//will show
g.drawString("Two", 40, 40);//will show
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleAttributes();
}
});
}
}
并覆盖JPanel