gpt4 book ai didi

java - 自定义 JPanel 未更新

转载 作者:行者123 更新时间:2023-11-30 07:52:51 25 4
gpt4 key购买 nike

代码:

import java.awt.BorderLayout;

import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class PaintWindow {

private JFrame frame;
private aJPanel panel;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PaintWindow window = new PaintWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application.
*/
public PaintWindow() {
initialize();
}

/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel = new aJPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);

JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.stam();
}
});
frame.getContentPane().add(btnNewButton, BorderLayout.NORTH);

frame.setBounds(100, 100, 450, 300);
frame.setVisible(true);
}

public class aJPanel extends JPanel {
private static final long serialVersionUID = 8874943072526915834L;
private Graphics g;

public aJPanel() {
super();
System.out.println("Constructor");
}

public void paint(Graphics g) {
super.paint(g);
System.out.println("paint");
g.fillRect(10, 10, 10, 10);
this.g = g;

}

public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("paintComponent");
g.fillRect(20, 20, 20, 20);
this.g = g;
}

public void stam() {
System.out.println("stam");
this.g.fillRect(40, 40, 40, 40);
this.repaint();
}
}
}

我想要做的是在用户单击按钮或触发鼠标事件后绘制自定义形状(线条、矩形等)。但调用 aJPanel.stam() 不会显示应有的矩形。我对 JPanel 还很陌生。有什么建议吗?

最佳答案

首先:

  1. 类名应以大写字母开头
  2. 类名应该是描述性的。

“aJPanel”不遵循上述任何一条。

but calling aJPanel.stam() does not show the rectangle its supposed to

参见Custom Painting Apporoaches动态绘画的两种常见方法:

  1. 将对象添加到列表并迭代列表以绘制所有对象
  2. 直接绘制 BufferedImage,然后绘制 BufferedImage

示例通过拖动鼠标来添加矩形,但您只需在单击按钮时调用 addRectangle(...) 方法即可轻松添加矩形。

关于java - 自定义 JPanel 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33123922/

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