将布局管理器与 JPanel 和 Graphics 2D 一起使用

Using Layout Manager with JPanel and Graphics 2D

我想在 JPanel 上绘制线条和更多内容,将其添加到 JFrame,然后使用 .pack()。我的问题是我不知道如何在特定情况下使用布局管理器。通常我使用 gridBagLayout 在面板上添加一个按钮或其他东西,我完全理解这一点。但是对于 2D 图形,我只是直接在面板上绘制。因此我不能正确使用 .pack() 。有人知道如何以正确的方式 pack() 那个 jPanel 吗?我的代码看起来像这样:

public class NetworkViewPanel extends JPanel implements KeyListener, ActionListener {       
public NetworkViewPanel(NetworkAI network) {
    this.network = network;
    this.netList = network.getLayerList();
    addKeyListener(this);
    setFocusable(true);
    this.setLayout(new GridLayout(2, 2, 2, 2)); // does that even make sense ?

}

public void paint(Graphics g) {
    super.paint(g);
    g2 = (Graphics2D) g;


    if (showStandardView) {
        drawRectangles();
        drawLines();
    } else {
        drawRectangles();
        drawLinesSpecial(listIndex, xIndex);
    }
}

你好:)

您可以使用布局管理器对 JPanel 进行布局,并在其上进行自定义绘制。
这不会阻止您使用 pack()1.
下面的 mre 2 演示了使用 GridLayoutJPanel 上画一条线:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class NetworkViewPanel extends JPanel{

    private final List<JLabel> labels;

    public NetworkViewPanel() {
        this.setLayout(new GridLayout(2, 2, 2, 2));
        this.setPreferredSize(new Dimension(400,300));//used by pack()
        labels = new ArrayList<>();
        addLabels(new String[]{ "A", "B" , "C" , "D"});
    }

    private void addLabels(String[] text){

        for(String t: text){
            JLabel label = new JLabel(t);
            label.setBorder(BorderFactory.createLineBorder(Color.BLUE));
            label.setHorizontalAlignment(JLabel.CENTER);
            add(label);
            labels.add(label);
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g); //draw panel as layed out by layout manager
        drawLines(g);
    }

    private void drawLines(Graphics g) {
        //draw line between centers of first and last components
        int x1 = labels.get(0).getBounds().x + labels.get(0).getBounds().width /2;
        int y1 = labels.get(0).getBounds().y + labels.get(0).getBounds().height /2;
        int x2 = labels.get(labels.size()-1).getBounds().x + labels.get(labels.size()-1).getBounds().width/2;
        int y2 = labels.get(labels.size()-1).getBounds().y + labels.get(labels.size()-1).getBounds().height/2;
        g.setColor(Color.RED);
        g.drawLine(x1, y1, x2, y2);
    }

    public static void main(String[] args) {

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLocationRelativeTo(null);
        f.add(new NetworkViewPanel());
        f.pack();
        f.setVisible(true);
    }
}


1 参见:What does .pack() do?
2 考虑在提问或回答时发布 mre