简体   繁体   中英

Java swing Paint method not being called

I've setup this really bare-bones View class to test out the Paint method from java swing. However, I noticed that even though I create an instance of view from another class and keep calling the update method below, the paint method is never executed. EDIT: I added code from main and controller.

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

public class View extends JPanel {

    //Attributes
    private static int frameWidth = 500;
    private static int frameHeight = 500;
    private JFrame frame; // the frame
    private JPanel menu;
    private JPanel game;
    private JPanel summary;


    //Constructor
    public View(ControlListener controlListener) {
        this.frame = new JFrame();
        frame.setLayout(new GridLayout(3,1));
        frame.addKeyListener(controlListener);
        frame.setTitle("MyFrame");
        frame.setBackground(Color.blue);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(frameWidth, frameHeight);
        frame.getContentPane().setBackground(Color.blue);
        frame.setVisible(true);

    }

    //Methods
    public JFrame getFrame() {
        return frame;
    }

    public static int getFrameWidth() {
        return frameWidth;
    }

    public static int getFrameHeight() {
        return frameHeight;
    }

    //frame updater
    public void update() {
        frame.repaint();

    }

    @Override
    public void paint(Graphics g) {
        System.out.println("test");
    }

Snippet from main:

public static void main(String[] args) {
    Controller v = new Controller();
    v.start();
}

Snippet from controller:

public class Controller {

    //Attributes
    private Model model;
    private View view;


    //Constructor
    public Controller(){
        view = new View(controlListener);

    }

    //run 
    public void start(){
        run();
    }

    public void run(){

        while(true){
            view.update();
    }
}

从来没有将View实例添加到JFrame中,因此Swing没有理由绘制不可见的组件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM