Wywołanie metody z parametrem "Graphics".

0

Stworzyłem pole JFrame oraz metodę mającą narysować białe kratki (bars). To może wydawać się głupie ale nie mam pojęcia jak ją zaimplementować w samym programie. Dzięki za pomoc !
Poniżej Kod

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;


public class MainGame {
 	public static final int Width = 800, Height = 700;
	
	public JFrame frame;

	public void bars(Graphics g){
			g.setColor(Color.white);
		for (int i=0; i < Width / 10; i++ ){
			g.drawLine(0, i *10 , 0, Height);
		}
		for (int i=0; i < Height / 10; i++ ){
			g.drawLine(0, i *10 , 0, Width);
		}
			
	}
	public MainGame() {
		
		frame= new JFrame("Snake");
		frame.setVisible(true);
		frame.setSize(Width, Height);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setBackground(new Color(40,40,40));
	}
	public static void main(String[] args) { 
		MainGame snake = new MainGame();
	}

}

Jest to fragment gry "Snake" którą krok po kroku staram się stworzyć.

1

Metodę już zaimplementowałeś, chodzi Ci o to jak ją wywołać? Wywołać ją można z metody paint (paintComponent), ta metoda z kolei wywoływana jest automatycznie. Musisz trochę przebudować program.

public class MainGame {
    public static final int Width = 800, Height = 700;
 
    public JFrame frame;
 
    public void bars(Graphics g){
            g.setColor(Color.white);
        for (int i=0; i < Width / 10; i++ ){
            g.drawLine(0, i *10 , 0, Height);
        }
        for (int i=0; i < Height / 10; i++ ){
            g.drawLine(0, i *10 , 0, Width);
        }
		g.drawLine(0,0,Width,Height);
 
    }
    public MainGame() {
 
        frame= new JFrame("Snake");


        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.add(new GamePanel());
		frame.pack();
		frame.setVisible(true);
    }
    public static void main(String[] args) { 
        MainGame snake = new MainGame();
    }
	class GamePanel extends JPanel{
		public GamePanel(){
			setPreferredSize(new Dimension(Width,Height));
			setBackground(new Color(40,40,40));
		}
		public void paintComponent(Graphics g){
			super.paintComponent(g);
			bars(g);
		}
	}
 
}

Masz złe parametry wywołania metody drawLine

0

Zauważyłem że dodałeś linię frame.pack();. zamiast frame.setSize(Width, Height);Skąd pobiera ona wymiary okna ?

1

Wylicza sobie wymiary, tworzy najmniejsze okno, które pomieści wszystkie komponenty. U Ciebie jest jeden komponent - panel o rozmiarach Width i Height.

1 użytkowników online, w tym zalogowanych: 0, gości: 1