为什么 JPanel(面板)不绘制在绿色背景(jpanel)上?我希望能够在不将 j 面板扩展到...的情况下执行此操作
此外,对于java游戏我应该在java中使用键绑定(bind)或键监听器。
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);
}
}
最佳答案
让我们看一下您的代码,并将 @Override
添加到您的 paintComponent
方法中...
public class Game {
//...
@Override
public void paintComponent(Graphics g) {
panel.paintComponents(g);
g.setColor(Color.RED);
g.drawRect(100, 10, 30, 40);
g.fillRect(10, 10, 20, 10);
}
}
现在我们遇到了编译器错误!这是因为 Game
扩展了 Object
并且没有 paintComponent
方法。这意味着现有绘画系统的任何部分都无法调用该方法,因此它永远不会被调用。
组件制作的“游戏”实体很差,它们有很多“管道”,这并不能让它们非常高效地完成此类工作,通常最好选择完整的自定义绘画路线
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Game {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Game().createGui();
}
});
}
JFrame window;
GamePanel 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);
panel = new GamePanel();
panel.setBackground(new Color(65, 130, 92));
window.add(panel);
window.setVisible(true);
return true; //returns true if ran and will be ran by check status in Main.
}
public class GamePanel extends JPanel {
private Rectangle entity = new Rectangle(100, 10, 30, 40);
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.draw(entity);
g2d.setColor(Color.BLUE);
g2d.fill(entity);
g2d.dispose();
}
}
}
另请注意,仅在将 panel
添加到 window
后,我才调用 window.setVisible(true);
,这是因为Swing 在添加/删除组件时很懒惰。如果你想在屏幕上实现 UI 后添加/删除组件,则需要在容器上调用 revalidate
和 repaint
来触发布局和绘制通过
另外,请注意,paintComponent
和 paintComponents
之间存在差异;)
我强烈建议您查看 Painting in AWT Swing和 Performing Custom Painting更好地了解 Swing 中绘画的工作原理以及如何利用它
关于java - 为什么 JPanel(面板)不绘制在绿色背景(jpanel)上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43174385/