簡體   English   中英

java JFrame圖形

[英]java JFrame graphics

我在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(..)

  • 而是將帶有覆蓋的paintComponent(Graphics g) 自定義 JPanel添加到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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM