如何在没有类(扩展JFrame)的情况下绘制对象?我找到了getGraphics方法,但它没有绘制对象.
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(600, 400);
JPanel panel = new JPanel();
frame.add(panel);
Graphics g = panel.getGraphics();
g.setColor(Color.BLUE);
g.fillRect(0, 0, 100, 100);
}
}
Run Code Online (Sandbox Code Playgroud) 我正在用cardLayout改变"视图"(这个类有一个JFrame变量).当用户点击新游戏按钮时会发生这种情况:
public class Views extends JFrame implements ActionListener {
private JFrame frame;
private CardLayout cl;
private JPanel cards;
private Game game;
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("New game")) {
cl.show(cards, "Game");
game.init();
this.revalidate();
this.repaint();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
game.loop();
}
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
游戏的循环方法和课程标题:
public class Game extends JPanel implements KeyListener {
public void loop() {
while (player.isAlive()) {
try {
this.update();
this.repaint();
// first class JFrame variable …Run Code Online (Sandbox Code Playgroud)