我相信这是一个简单的答案,但我想不通。
我正在尝试制作一个可以在窗口中控制的基本形状。很明显,当整个项目完成时,它会更多地参与进来,但我仍在进行早期步骤。我正在使用WindowBuilder进行布局,并且有一个JPanel和一个JButton。JPanel绘制一个矩形,并有一个移动它的方法。JButton调用该移动命令。就是这样。问题出在重新油漆上。该形状保留了所有旧版本的自身,而按钮则对自身进行了奇怪的复制。当我调整窗口大小时,所有这些都会消失,我认为这与调用重新绘制相同。再说一次,我确信我错过了一些简单的东西。下面是我的两堂课。
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Drawing {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Drawing window = new Drawing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Drawing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
drawpanel panel = new drawpanel();
panel.setBounds(58, 68, 318, 182);
frame.getContentPane().add(panel);
JButton btnMove = new JButton("move");
btnMove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.moves();
}
});
btnMove.setBounds(169, 34, 89, 23);
frame.getContentPane().add(btnMove);
}
}
^除了buttonListener之外,这个也是由WindowBuilder自动创建的。
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class drawpanel extends JPanel {
int x = 50, y = 50;
int sizeX = 50, sizeY = 50;
public void paintComponent( Graphics g) {
super.paintComponents(g);
g.setColor(Color.BLACK);
g.drawRect(x, y, sizeX, sizeY);
}
public void moves() {
x +=5;
repaint();
}
}
^这个有我画的形状和移动/重新喷漆的方法。它主要是根据我在这个网站上找到的其他例子写的。
感谢您的帮助。
public void paintComponent(Graphics g) {
super.paintComponents(g); // wrong method! (Should not be PLURAL)
应为:
public void paintComponent(Graphics g) {
super.paintComponent(g); // correct method!