【发布时间】:2012-11-04 04:45:42
【问题描述】:
当我运行我的代码时,我希望在我的JFrame 中看到一个JPanel,但没有任何显示。我在框架中有一个按钮,它会显示出来。但是JPanel 没有出现,我什至把它涂成红色。
这是我的JPanel的代码:
import java.awt.*;
import javax.swing.JPanel;
public class graphic extends JPanel {
private static final long serialVersionUID = -3458717449092499931L;
public Game game;
public graphic(Game game){
this.game = game;
this.setPreferredSize(new Dimension(400,400));
this.setBackground(Color.RED);
}
public void paintComponent(Graphics g){
for (Line l:game.mirrors){
g.setColor(Color.BLACK);
g.drawLine(l.start.x, l.start.y, l.end.x, l.end.y);
}
}
}
还有我的 JFrame 代码:
import java.awt.Container;
import java.awt.event.*;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.*;
public class Viewer implements ActionListener {
public JFrame frame;
public JButton drawShoot;
public boolean draw;
public Game game;
public graphic graphic;
public TimerTask timert;
public Timer timer;
public Viewer(){
draw = true;
game = new Game();
}
public static void main(String args[]){
Viewer v = new Viewer();
v.setup();
}
public void setup(){
frame = new JFrame("Laser Stimulator");
drawShoot = new JButton("Edit Mode");
graphic = new graphic(game);
graphic.repaint();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(300, 300, 600, 600);
Container contentPane = frame.getContentPane();
SpringLayout layout = new SpringLayout();
contentPane.setLayout(layout);
drawShoot.addActionListener(this);
timert = new TimerTask() {
@Override
public void run() {
}
};
timer =new Timer();
timer.scheduleAtFixedRate(timert, 0, 1000/30);
contentPane.add(graphic);
layout.putConstraint(SpringLayout.NORTH, graphic, 0, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, graphic, 0, SpringLayout.WEST, contentPane);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==drawShoot){
draw = !draw;
drawShoot.setText((draw)?"Edit Mode":"Shoot Mode");
}
}
}
【问题讨论】:
-
将框架的布局改为 BorderLayout 之类的东西
-
为什么? Borderlayout 非常难以使用,我使用 spring 布局,因为它看起来更好。
-
因为我试图让窗格正确显示...;)
-
这不是制作游戏的正确方式。性能游戏,直接在
JFrame上创建BufferStrategy并将其用于渲染。
标签: java swing jframe jpanel paintcomponent