从代码中可以看到,我希望在DrawingPanel上看到一个矩形,但是我不确定为什么repaint()方法不起作用。任何帮助都感激不尽。我也尝试过revalidate方法,但该方法也不起作用。

这是我的课程:

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

public class Designer extends JFrame {

static JFrame f = new Designer();

JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
DrawingPanel drawingPanel = new DrawingPanel();
PropertyPanel propertyPanel = new PropertyPanel();

 public Designer(){

    Rectangle bounds = GraphicsEnvironment
            .getLocalGraphicsEnvironment()
            .getMaximumWindowBounds();

    splitPane.setTopComponent(propertyPanel);
    splitPane.setBottomComponent(drawingPanel);

    add(splitPane, BorderLayout.CENTER);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(bounds);
    setVisible(true);

 }

 public static void main(String[] args) {
    System.out.println("App started...");
 }
}


第一个Jpanel的类:PropertyPanel.Java

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

public class PropertyPanel extends JPanel {

  private DrawingPanel drawingPanel = new DrawingPanel();

  public PropertyPanel(){

    JButton addShapesBtn = new JButton("Add");

    addShapesBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            drawingPanel.addRectangle();
        }
    });
    add(addShapesBtn);
  }

}


第二个Jpanel的类:DrawingPanel.Java

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class DrawingPanel extends JPanel{

  private List<Rectangle> squares = new ArrayList<Rectangle>();


 @Override
 protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D) g;

    System.out.println("painting");

    for (Rectangle rect : squares) {
        g2.draw(rect);
    }

}


  public void addRectangle() {

    Rectangle rectx = new Rectangle(10, 10, 100, 100);
    squares.add(rectx);
    repaint(); <-- this is not working
  }
}

最佳答案

您的重新粉刷效果很好。您的问题是您正在调用addRectangle()到错误的DrawingPanel实例,而不是当前在GUI中显示的实例。要解决此问题,请将引用从显示的引用传递到需要调用该方法的代码。

要确认这是正确的,只需在此页面上搜索new DrawingPanel()。您应该只在自己的代码(和发布的代码)中看到一次。您会看到两次,这意味着您已经创建了两个实例。

例如,更改此:

public class PropertyPanel extends JPanel {
    private DrawingPanel drawingPanel = new DrawingPanel();

    public PropertyPanel(){


对此:

public class PropertyPanel extends JPanel {
    private DrawingPanel drawingPanel;  // don't create new

    public PropertyPanel(DrawingPanel drawingPanel){
        this.drawingPanel = drawingPanel;


然后在创建时将真实的DrawingPanel传递到此对象中:

DrawingPanel drawingPanel = new DrawingPanel();
PropertyPanel propertyPanel = new PropertyPanel(drawingPanel);




更好的是:以M-V-C的方式来构造代码,并使用依赖注入来建立连接-但这对于您的简单GUI可能是过大的。

07-28 13:01