我已经设置了这个真正的准系统View类,以测试Java swing中的Paint方法。但是,我注意到,即使我从另一个类创建视图实例并继续调用下面的update方法,paint方法也永远不会执行。编辑:我添加了从主和控制器的代码。
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");
}
主站摘录:
public static void main(String[] args) {
Controller v = new Controller();
v.start();
}
控制器的摘录:
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();
}
}
答案 0 :(得分:1)
从来没有将View实例添加到JFrame中,因此Swing没有理由绘制不可见的组件。