gpt4 book ai didi

java JFrame 图形

转载 作者:行者123 更新时间:2023-12-02 09:18:38 31 4
gpt4 key购买 nike

我在 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[font=java.awt.Font[family=Dialog,name=Dialog,style=plain,size=12],color=java.awt.Color[r=255,g=0,b=0]]

但是 JFrame 上没有绘制红色多边形,而只是空白的 JFrame。

为什么?

最佳答案

  • 不要覆盖 JFrame 中的paint(..)

  • 而是将自定义 JPanel 与覆盖的 paintComponent(Graphics g) 添加到 JFrame

  • 不要使用Null/AbsoluteLayout use an appropriate 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);
}
}

产生:

enter image description here

关于java JFrame 图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13075417/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com