为什么不在绿色背景(jpanel)上绘制JPanel(面板)?我希望能够在不将j面板扩展到......的情况下做到这一点。
此外,对于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);
}
}
答案 0 :(得分:1)
让我们将您的代码暂存,并将@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();
}
}
}
另请注意,我在将window.setVisible(true);
添加到panel
后才调用window
,这是因为在添加/删除组件时Swing很懒。如果要在屏幕上实现UI后添加/删除组件,则需要在容器上调用revalidate
和repaint
以触发布局和绘制传递
另外,请注意,paintComponent
和paintComponents
之间存在差异;)
我强烈建议您查看Painting in AWT Swing和Performing Custom Painting,以便更好地了解Swing中的绘画效果以及如何利用它