为什么JPanel(面板)不能在绿色背景(jpanel)上绘制?我希望能够做到这一点,而无需扩展j面板...为什么JPanel(面板)不能在绿色背景(jpanel)上绘制?
此外,对于java游戏,我应该在java中使用keybindings或keylistener。
import javax.swing.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class Game {
JFrame window;
JPanel panel;
int charPosX = 0;
int charPosY = 0;
public Boolean createGui() {
window = new JFrame("Game");
window.setSize(1000,500);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
panel = new JPanel();
panel.setVisible(true);
panel.setLayout(null);;
panel.setBackground(new Color(65,130,92));
window.add(panel);
return true; //returns true if ran and will be ran by check status in Main.
}
public void paintComponent(Graphics g) {
panel.paintComponents(g);
g.setColor(Color.RED);
g.drawRect(100,10,30,40);
g.fillRect(10, 10, 20, 10);
}
}
问自己这个问题,谁是真正的调用你的'paintComponent'方法?也许在你的'paintComponent'中添加'@ Override'并且看看它的作用 – MadProgrammer
Shell,我们还讨论了这个事实:你的'panel'没有可定义的大小,也不能管理你可能添加的任何子组件。作为一般性建议,我会避免以这种方式使用组件,并通过自定义绘画方法实现功能,因为它更高效且不易出错 – MadProgrammer
定制绘画方法意味着什么? ???? – Blockeus