java JFrame 图形 [英] java JFrame graphics
问题描述
我在 JFrame 构造函数中有以下简单代码
I have the following simple code in a JFrame constructor
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);
我在控制台上得到的输出为:
I get the output on console as:
sun.java2d.SunGraphics2D[font=java.awt.Font[family=Dialog,name=Dialog,style=plain,size=12],color=java.awt.Color[r=255,g=0,b=0]]
sun.java2d.SunGraphics2D[font=java.awt.Font[family=Dialog,name=Dialog,style=plain,size=12],color=java.awt.Color[r=255,g=0,b=0]]
但在 JFrame 上没有绘制红色多边形,只有空白的 JFrame.
But no red polygon drawn on JFrame but just the blank JFrame.
为什么??
推荐答案
不要覆盖
JFrame
而是将带有覆盖的
paintComponent(Graphics g)
的 customJPanel
添加到JFrame
Rather add custom
JPanel
with overriddenpaintComponent(Graphics g)
toJFrame
不要使用
Null
/AbsoluteLayout
使用合适的LayoutManager
Dont use
Null
/AbsoluteLayout
use an appropriateLayoutManager
不要在
JFrame
实例上调用setBounds(..)
(不是不允许,但在这个应用程序中看不到它是相关的)Dont call
setBounds(..)
onJFrame
instance (not that its not allowed but cant see it being relevant in this application)不要忘记使用 EDT 来创建并更改 GUI 组件:
Dont forget to use EDT for creating and changing GUI components:
javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Test test = new Test(); } });
然后你会做这样的事情:
you would then do something like this:
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);
}
}
产生:
这篇关于java JFrame 图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!