2013-07-14 61 views
1

當我運行這個程序時,我看到的只是一個空白的JFrame。我不知道爲什麼paintComponent方法不起作用。這裏是我的代碼:爲什麼我不能繪製到我的JPanel?

package com.drawing; 

import java.awt.Color; 
import java.awt.Graphics; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class MyPaint extends JPanel { 

    private void go() { 
     JFrame frame = new JFrame(); 
     JPanel panel = new JPanel(); 
     frame.setSize(400, 400); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLocationRelativeTo(null); 
     frame.add(panel); 
     frame.setVisible(true); 
    } 

    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.setColor(Color.YELLOW); 
     g.fillRect(50, 50, 100, 100); 
    } 

    public static void main(String[] args) { 
     My paintTester = new MyPaint(); 
     paintTester.go(); 
    } 
} 
+0

使用'this',而不是''中去(panel')' – chaosmasttter

+1

另外,爲什麼沒有JFrame的方法和JPanel有兩個不同的類? –

+0

只是一個建議,而不是在'JFrame'上設置大小,如果您重寫[__getPreferredSize()__](http://docs.oracle.com/javase/7/docs/api/javax/swing /JComponent.html#getPreferredSize()),就像重寫'paintComponent()'方法並調用'frame.pack()' –

回答

4

你必須要做到這一點

private void go() { 
     JFrame frame = new JFrame(); 
     frame.setSize(400, 400); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLocationRelativeTo(null); 
     frame.add(this); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

,但我會重構你的等級和獨立responsabilities ..

go()不應該在這個類

public class MyPaint extends JPanel { 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.setColor(Color.YELLOW); 
     g.fillRect(50, 50, 100, 100); 
    } 

} 

而在另一聲明

// In another class 
public static void main(String[] args) { 
    JPanel paintTester = new MyPaint(); 
    JFrame frame = new JFrame(); 
    frame.setSize(400, 400); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLocationRelativeTo(null); 
    frame.add(paintTester); 
    frame.pack(); 
    frame.setVisible(true); 
} 

或者,如果你只是要使用此面板在一個網站,你可以採取匿名類

 JFrame frame = new JFrame(); 
    frame.add(new JPanel(){ 
     @Override 
     public void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      g.setColor(Color.YELLOW); 
      g.fillRect(50, 50, 100, 100); 
     } 

    }); 
+0

工作!謝謝!但是在這種情況下究竟是指「這個」呢?它是指JPanel,我之前提出了一個新對象嗎?我的班級結構有什麼問題?對不起,當談到以一種很好的面向對象的方式來設計程序時,我有些不自在。 –

+0

@BillyJean我編輯我的答案,希望它可以幫助..'this'指的是'你這種類的'這個類的實例你創建的類 – nachokk

+0

噢好吧,陷阱。謝啦! –

2

您要添加一個普通JPanelJFrame不包含您的自定義油漆邏輯。刪除

JPanel panel = new JPanel(); 

,並添加

frame.add(this); 

而且更好地保持2類:一類主要和定製JPanel油漆邏輯separation of concerns

+1

我真的認爲,他可以添加'這個' – nachokk

+0

這兩個建議的工作!非常感謝!!但是我究竟做錯了什麼?香草是否意味着它是一個原始的JPanel? –

+0

您正在添加一個不實現自定義繪畫邏輯的組件(如前所述)。順便說一句:_vanilla_意味着[平原](http://www.thefreedictionary.com/plain+vanilla),在這種情況下,沒有實現自定義繪畫。 – Reimeus

相關問題