0
我一直無法讓繪圖組件在第三個屏幕上繪製任何東西。我用這個簡單的代碼測試過它,發現了一件事。如果我將矩形的座標設置爲0,0,那麼一個小的小點出現在屏幕的中間頂部,大小應該是它的一小部分。JPanel在使用cardLayout時不會顯示paintComponent
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class hello extends JPanel {
public int[][] room = new int[20][20];// Whether the room is solid or hollow
public static Random r = new Random();
boolean toggle, GameEnable;
int i, j, px, py, temp, endx, endy;
private static final long serialVersionUID = 1L;
JFrame f = new JFrame("Maze Game");
JPanel p0 = new JPanel();
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JButton b1 = new JButton("Screen 2");
JButton b2 = new JButton("Give Visuals");
CardLayout cl = new CardLayout();
public void Game() {
p0.setLayout(cl);
p1.add(b1);
p2.add(b2);
p3.add(new GameVisual());
p1.setBackground(Color.RED);
p2.setBackground(Color.BLACK);
p4.setBackground(Color.PINK);
p0.add(p1, "1");
p0.add(b2, "2");
p0.add(p3, "3");
p0.add(p4, "4");
cl.show(p0, "1");
final Timer timer = new Timer(10 * 60 * 1000, new ActionListener() {
public void actionPerformed(final ActionEvent e) {
cl.show(p0, "4");
}
});
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cl.show(p0, "2");
}
});
b2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cl.show(p0, "3");
timer.start();
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(816, 816);
f.setVisible(true);
f.setLocationRelativeTo(null);
f.add(p0);
timer.start();
}
class GameVisual extends JPanel { //This is a sub class not a separate class file
private static final long serialVersionUID = 2L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(10,10, 400, 400);
}
}
public static void main(String[] args) {
new hello().Game();
}
}
所以我的問題是,爲什麼不apearing我的paintComponent的屏幕(或大小的位置不正確的分數顯示,我怎麼可能會解決這個問題。 PS如果可能的話我想保留一切在同一班上,而不是把它們放到不同的班級,因爲我使用數組來做大部分我的繪畫在這個代碼的較大版本。
好的,所以當它到達第三個屏幕時,它會調整屏幕大小以適應視覺?我的理解正確嗎? – MrFAYAZ666
是的。作爲一個測試,不要使用上面顯示的setPreferredSize()方法。相反,只需將組件添加到GameVisual。您將看到藍色矩形增長,因爲JPanel必須增長以適應組件。我不知道你最終的GameVisual面板應該是什麼樣子,但它會增長以適合你添加到它的組件。 –