它不会画线

It won't draw the line

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

class Game4 extends JPanel {
  public Game4() {
    setVisible(true);
  }

  public void paint(Graphics g) {
    Graphics2D twoD = (Graphics2D) g; 
    boxes(twoD);
  }

  public void boxes(Graphics2D twoD) {
    twoD.drawLine(getWidth() / 3, 0, getWidth() / 3, getHeight());
  }
}

出于某种原因,我无法提取此代码。我不太擅长 Graphics2D 所以如果我能得到一些帮助那就太好了。

首先查看 Painting in AWT and Swing and Performing Custom Painting 以了解有关如何在 Swing 中绘制的更多详细信息。

paint 做了很多非常重要的工作,比如根据组件 foreground 颜色设置 Graphics 上下文的默认颜色,填充背景,设置剪辑,等等

除非你真的愿意接管所有的控制权,否则你最好避免它。相反,更喜欢使用 paintComponent.

您可能还需要为组件提供一些基本的大小调整提示,并且为了在屏幕上显示组件需要添加到某种 window(即 JFrame )

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {
        public TestPane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            boxes(g2d);
            g2d.dispose();
        }

        protected void boxes(Graphics2D twoD) {
            twoD.drawLine(getWidth() / 3, 0, getWidth() / 3, getHeight());
        }

    }
}