java JFrame图形
我在JFrame构造函数中有以下简单代码
super(name); setBounds(0,0,1100,750); setLayout(null); setVisible(true); g = this.getGraphics(); int[] x =new int[]{65, 122, 77, 20, }; int[] y =new int[]{226, 258, 341, 310}; g.setColor(Color.RED); g.drawPolygon (x, y, x.length); System.out.println(g);
我在控制台上获得输出:
sun.java2d.SunGraphics2D [字体= java.awt.Font中[家族=对话框,名称=对话框,风格=平原,大小= 12],颜色= java.awt.Color中[R = 255,G = 0,B = 0 ]]
但是在JFrame上没有绘制红色多边形,只有空白JFrame。
为什么?
-
不要在
JFrame
覆盖paint(..)
-
而是将自定义
JPanel
与重写的paintComponent(Graphics g)
到JFrame
-
不要使用
Null
/AbsoluteLayout
使用适当的LayoutManager
-
不要在
JFrame
实例上调用setBounds(..)
(不是它不允许但是不能看到它在这个应用程序中是相关的) -
别忘了使用EDT创建和更改GUI组件:
javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Test test = new Test(); } });
然后你会做这样的事情:
public class Test { /** * Default constructor for Test.class */ public Test() { initComponents(); } public static void main(String[] args) { /** * Create GUI and components on Event-Dispatch-Thread */ javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Test test = new Test(); } }); } /** * Initialize GUI and components (including ActionListeners etc) */ private void initComponents() { JFrame jFrame = new JFrame(); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.add(new MyPanel()); //pack frame (size JFrame to match preferred sizes of added components and set visible jFrame.pack(); jFrame.setVisible(true); } } class MyPanel extends JPanel { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int[] x = new int[]{65, 122, 77, 20}; int[] y = new int[]{226, 258, 341, 310}; g.setColor(Color.RED); g.drawPolygon(x, y, x.length); } //so our panel is the corerct size when pack() is called on Jframe @Override public Dimension getPreferredSize() { return new Dimension(400, 400); } }
产生:
你应该比你正在尝试的方法更好地覆盖paint(Graphics g)
或paintComponent(Graphics g)
。 添加下面的行并删除代码中setVisible
后的行。
public void paint(Graphics g) { int[] x =new int[]{65, 122, 77, 20}; int[] y =new int[]{226, 258, 341, 310}; g.setColor(Color.RED); g.drawPolygon (x, y, x.length); }