[英]Why doesn't JPanel (panel) get drawn on the green background (the jpanel)?
為什么JPanel(面板)沒有繪制在綠色背景(Jpanel)上? 我希望能夠做到這一點而無需將j面板擴展到...
此外,對於Java游戲,我應該在Java中使用快捷鍵或快捷鍵。
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();
}
}
}
還要注意,我叫window.setVisible(true);
僅在將panel
添加到window
,這是因為在添加/刪除組件時,Swing會很懶。 如果要在屏幕上實現UI后添加/刪除組件,則需要在容器上調用revalidate
和repaint
以觸發布局和繪制過程
另外,請注意, paintComponent
和paintComponents
之間是有區別的;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.