2017-11-09 8 views
0

これを実行すると、ウィンドウが表示され、描画されません。 プログラムを起動すると、終了コードがヌルであるがウィンドウが空になったときに実行されます。Jframeが正しく動作しない

public class Component extends JComponent implements IComponent { 
    public void init(Graphics g) { 
    int cellWidth = 7; 
    int cellHeight = 7; 
     // Background: 
     super.paintComponent(g); 
     g.setColor(Color.white); 
     for (int i = 0; i <= 5; i++) { 
      for (int j = 0; j <= 5; j++) {    
       g.setColor(Color.black); 
       g.fillRect(i * cellWidth, j * cellHeight, cellWidth, cellHeight); 
       g.setColor(Color.decode("#00ffff")); 
       g.fillRect(i * cellWidth, j * cellHeight, cellWidth - borderThickness, cellHeight - borderThickness); 
      } 
     } 
     g.setColor(Color.BLACK); 
    } 

    public void draw() { 
     JFrame f = new JFrame("Test"); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     Component c = new Component(gameStatus); 
     f.add(c); 
     f.setSize(screenWidth, screenHeight); 
     f.setVisible(true); 
    }} 


public class app { 
public static void main(String[] args) { 
    Component component = new Component(gameStatus); 
    component.draw(); 
}} 
+1

[mcve]を投稿してください。あなたの現在投稿されているコードがたくさんありません。 how/where/whenは 'init(Graphics)'と呼ばれますか?代わりに 'paintComponent()'をオーバーライドしたくないのですか? – Thomas

+0

sry mate私のコードを今このように編集する – Boyesz

+1

私は強く** [JFC/Swing](https://docs.oracle.com/javase/tutorial/uiswing/index.html)チュートリアルあなたがまだいなければ。私は欠けているいくつかの重要な初期化コードがあると考えているので、それがレンダリングされていません。このチュートリアルでは、Swingアプリケーションを読みやすく、コード化するのをはるかに簡単にする推奨された方法についていくつか提案しています。 –

答えて

1

カスタム図面を作成するには、paintComponent(Graphics g)をオーバーライドする必要があります。また、あなたはコンポーネント格納の周りに混乱があるようです - それを作成し、別の内部draw()を作成します。

これらの問題を修正すると、これはうまくいくように見えます。定数):

import javax.swing.*; 
import java.awt.*; 

public class Component extends JComponent { 
    static final int cellWidth = 7; 
    static final int cellHeight = 7; 
    static final int borderThickness = 1; 

    @Override 
    protected void paintComponent(Graphics g) { 
     // Background: 
     super.paintComponent(g); 

     for (int i = 0; i <= 5; i++) { 
      for (int j = 0; j <= 5; j++) { 
       g.setColor(Color.BLACK); 
       g.fillRect(i * cellWidth, j * cellHeight, cellWidth, cellHeight); 

       g.setColor(Color.CYAN); 
       g.fillRect(i * cellWidth + borderThickness, j * cellHeight + borderThickness, 
          cellWidth - 2 * borderThickness, cellHeight - 2 * borderThickness); 
      } 
     } 

     g.setColor(Color.BLACK); 
    } 

    public static void main(String[] args) { 
     Component component = new Component(); 

     JFrame f = new JFrame("Test"); 
     f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     f.setContentPane(component); 
     f.setSize(500, 500); 
     f.setVisible(true); 
    } 
} 
+0

ありがとうございました! :) – Boyesz

関連する問題