我试图弄清楚如何repaint()
扩展JComponent
. 我想让每个类扩展JComponent
,然后提供自己的paintComponent()
. (super.paintComponent()
。这样我可以制作一个圆形类或任何我想要制作的类,然后我可以repaint()
在任何时候只要将它添加到JPanel
.JFrame
下面是所有需要的代码跑步。
第一类:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class DDHGenericFrame extends JFrame {
private static final long serialVersionUID = 1L;
/* User defined class that is below */
DDHGenericPanel d = new DDHGenericPanel();
public DDHGenericFrame() {
initUI();
}
public final void initUI() {
add(d);
setSize(650, 350);
setTitle("Lines");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
DDHGenericFrame ex = new DDHGenericFrame();
ex.setVisible(true);
}
}
第 2 类:
import java.awt.Graphics;
import javax.swing.JPanel;
class DDHGenericPanel extends JPanel {
private static final long serialVersionUID = 1L;
DDHGenericPanel() {
System.out.println("DDH Generic JPanel");
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//paint code goes here of whatever
}
}
第 3 类:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class DDHCircleOne extends JComponent {
private static final long serialVersionUID = 1L;
int counter = 0;
public DDHCircleOne() {
counter++;
System.out.println("DDHCircle Constructor");
}
public void paintComponent(Graphics g2) {
super.paintComponent(g2);
Graphics2D c2D = (Graphics2D) g2;
c2D.setColor(Color.yellow);
c2D.fillRect(0, 0, getSize().width, getSize().height);
if (counter % 2 == 2) {
System.out.println("RED");
counter++;
c2D.setColor(Color.red);
c2D.fillRect(0, 0, getSize().width, getSize().height);
} else {
System.out.println("BLUE");
counter++;
c2D.setColor(Color.blue);
c2D.fillRect(0, 0, getSize().width, getSize().height);
}
}
}
以上三个类是我的包中的。我希望DDHCircleOne
能够在创建它的实例并调用方法时自行重绘它repaint()
。这样我就可以创建一个扩展类,JComponent
然后覆盖paintComponent()
然后调用repaint()
.
如果我有一个按钮以红色重绘,而另一个按钮以蓝色重绘,则圆圈或框架中的任何内容将在variableName.repaint()
调用时自行重绘。
donauf@outlook.com