相关疑难解决方法(0)

使用getGraphics()绘制对象而不扩展JFrame

如何在没有类(扩展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)

java swing graphics2d paintcomponent

9
推荐指数
1
解决办法
5万
查看次数

Java游戏循环(绘画)冻结了我的窗口

我正在用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)

java swing

6
推荐指数
1
解决办法
1371
查看次数

标签 统计

java ×2

swing ×2

graphics2d ×1

paintcomponent ×1