从代码中我可以看到我希望在DrawingPanel上看到一个矩形,但我不确定为什么repaint()方法不起作用。任何帮助都感激不尽。我也尝试过revalidate方法,但这也不起作用。
以下是我的课程:
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的类: PropertyPanel.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
}
}
第二个Jpanel的类: DrawingPanel.Java
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{B64EE74D-F171-4438-8E7A-ACAE7B40C6C8}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Olbert.CommunityScanner</RootNamespace>
<AssemblyName>CommunityScannerTopShelf</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
答案 0 :(得分:2)
你的重画工作正常。您的问题是,您正在向{strong>错误的 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方式构建代码,并使用依赖注入来建立连接 - 但这对于简单的GUI来说可能是过度的。