gpt4 book ai didi

java - Swing Java 重绘无法使用 2 个 jpanels 工作

转载 作者:行者123 更新时间:2023-11-30 02:16:48 25 4
gpt4 key购买 nike

正如您从代码中看到的,我希望在 DrawingPanel 上看到一个矩形,但我不确定为什么 repaint() 方法不起作用。任何帮助都感激不尽。我也尝试过重新验证方法,但这也不起作用。

这是我的类(class):

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
}
}

最佳答案

你的重画效果很好。您的问题是您正在对错误 DrawingPanel 实例调用 addRectangle() ,而不是当前在 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 方式构建代码,并使用依赖注入(inject)来建立连接——但这对于简单的 GUI 来说可能有点过分了。

关于java - Swing Java 重绘无法使用 2 个 jpanels 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48129735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com