我正在做一个java家庭作业。赋值是获取50个随机整数的数组,并绘制高度为每个成员大小的矩形或线条。单击JPanel时,选择排序将对数组进行排序并重新绘制矩形,这次按从最小到最大的顺序排列。我有drawPass方法绘制所有矩形。赋值需要我从paintComponent方法调用drawPass方法。我的问题是我无法在paintComponent中调用我的drawPass,因为drawPass需要有一个图形对象,但paintComponent没有任何参数。 Netbeans强调了drawPass();在我的paintComponent方法中,它说“required:Graphics,found:no arguments”。如何从paintComponent调用drawPass或任何建议的任何帮助将不胜感激。
package hw10;
import static java.awt.Color.RED;
import java.awt.Graphics;
import java.util.Random;
/**
*
* @author tshade
*/
public class AnimatedSelectionSortPanel extends javax.swing.JPanel {
int[] numbers = new int[50];
/**
* Creates new form AnimatedSelectionSortPanel
*/
public AnimatedSelectionSortPanel() {
initComponents();
}
private void loadArray() {
for (int i = 0; i < 50; i++) {
Random rnd = new Random(200 - 20);
int r = rnd.nextInt();
numbers[i] = r;
}
}
private void selection() {
for (int top = 0; top <= numbers.length - 2; top++) {
swapElements(top, findMinIndex(top));
}
}
private int findMinIndex(int startAt) {
int minIndex = startAt;
for (int index = startAt + 1; index <= numbers.length - 1; index++) {
if (numbers[index] < numbers[minIndex]) {
minIndex = index;
}
}
return minIndex;
}
private void swapElements(int index1, int index2) {
int tmp = numbers[index1];
numbers[index1] = numbers[index2];
numbers[index2] = tmp;
}
private void drawPass(Graphics g) {
super.paintComponent(g);
int x = 10;
for (int i = 0; i < 50; i++) {
int height = numbers[i];
g.setColor(RED);
g.drawRect(x, 250 - height, 1, height);
x = x + 10;
}
}
protected void paintComponent() {
if (numbers == null) {
loadArray();
drawPass();
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 613, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 235, Short.MAX_VALUE)
);
}// </editor-fold>
private void formMouseClicked(java.awt.event.MouseEvent evt) {
paintComponent();
selection();
repaint();
}
// Variables declaration - do not modify
// End of variables declaration
}
答案 0 :(得分:3)
我的问题是我无法在paintComponent中调用我的drawPass,因为drawPass需要有一个图形对象,但paintComponent没有任何参数。
确实它会收到Graphics
个对象。您没有在类中正确覆盖paintComponent(...)方法。
阅读Custom Painting上的Swing教程中的部分以获取更多信息和working
示例。或者您可以使用“paintComponent”搜索论坛。你会发现成千上万的自定义绘画的例子。
此外,您应该never
尝试直接调用paintComponent(...)方法。
答案 1 :(得分:0)
如果你在paintComponent方法上写@override,你会发现paintComponent有图形参数
)