简体   繁体   English

Java-paintComponent将不会在JPanel上显示工程图

[英]Java - paintComponent won't show drawings on JPanel

I've gotten stuck trying to draw on a JPanel . 我被困在尝试绘制JPanel I've learned how to create a JFrame , a JPanel , add event handlers, do the same in applets, and some other basic GUI development. 我已经学习了如何创建JFrameJPanel ,添加事件处理程序,在applet中进行相同的操作以及其他一些基本的GUI开发。 But everytime I try to draw on a JPanel using the paintComponent(Graphics g) or paint(Graphics g) methods, nothing shows up. 但是每次我尝试使用paintComponent(Graphics g)paint(Graphics g)方法在JPanel上绘制时,都不会显示任何内容。 Buttons, as well as other JComponents , show up just fine. 按钮以及其他JComponents都可以正常显示。 But g.drawString , g.drawRect , etc result in a blank JFrame window. 但是g.drawStringg.drawRect等导致空白的JFrame窗口。

Here is my code: 这是我的代码:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;

public class Game extends JPanel {
    public static void main(String[] args) {
        new Game().game();
    }

    JPanel panel;
    JButton button2;
    JButton button;

    public void game() {
        panel = new JPanel();
        button = new JButton("Ok");
        panel.setLayout(new FlowLayout());
        panel.add(button);

        button2 = new JButton("Cancel");

        JFrame frame = new JFrame("Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500,500);
        frame.setResizable(false);
        frame.add(panel);

        frame.setVisible(true); 
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString("hi",100,100);
        g.fillRect(100,50,200,300)
    }
}

The JPanel you're adding to your JFrame is a plain vanilla JPanel , not an instance of Game , your custom class that contains the paintComponent() method. JPanel您要添加到您JFrame是一个普通JPanel ,而不是一个实例Game ,自定义类包含paintComponent()方法。 YOu need to change that one line to 您需要将该行更改为

JPanel panel = new Game();

and you should see a difference immediately! 并且您应该立即看到差异!

The instance of Game you create in main() isn't being used for anything, other than calling the game() method. 您在main()创建的Game实例除了调用game()方法外,没有任何其他用途。 You could use it, if you wanted, by doing this instead: 如果需要,您可以通过执行以下操作来使用它:

JPanel panel = this;

and then proceeding as before. 然后像以前一样进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM