我正在试图找出如何对扩展repaint()的类进行JComponent。我希望每个类都扩展JComponent,然后提供自己的paintComponent()。(super.paintComponent().通过这种方式,我可以创建一个循环类或任何我想创建的类,然后只要它被添加到repaint()中的JPanel中,我就可以在任何时候使用它。下面是运行所需的所有代码。
第1类:
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()时,圆圈或我在框架中的任何东西都会重新绘制自己。
doughauf@outlook.com
发布于 2013-11-10 20:57:58
public void paintComponent(Graphics g) {
super.paintComponent(g);
repaint();
}永远不要在绘图方法中调用Never ()。这将导致无限循环。
没有必要使用通用面板。您可以向任何面板添加组件。
如果希望更改圆圈的颜色,则需要更改组件的属性。例如,您可以只使用setForeground(.)方法更改颜色:
//c2D.setColor(Color.red);
c2D.setColor( getForeground() );因此,当您单击按钮时,只需调用circle.setForeground(Color.RED);
setForeground()方法的JComponent将为您调用组件上的repaint()方法。
https://stackoverflow.com/questions/19894835
复制相似问题