【发布时间】:2016-02-19 12:21:16
【问题描述】:
我一直无法让绘制组件在第三个屏幕上绘制任何内容。我已经用这么简单的代码对其进行了测试,并发现了一件事情。如果我将矩形的坐标设置为 0,0,那么屏幕的中间顶部会出现一个小点,其大小是它应该的一小部分。
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();
}
}
所以我的问题是为什么我的paintcomponent 没有在屏幕上显示(或在错误位置显示尺寸的一小部分,我该如何解决这个问题。 附言如果可能的话,我希望将所有内容都放在同一个类中,而不是将它们放入单独的类中,因为我使用数组在此代码的较大版本中完成大部分绘画。
【问题讨论】:
标签: java jframe jpanel paintcomponent cardlayout