package harjutamine;
public class algandmed{
Button[] whitebutton= new Button[2];
Button[] blackbutton= new Button[2];
public algandmed(){
whitebutton[0] = new Button(5, 1);
whitebutton[1] = new Button(5, 3);
blackbutton[0] = new Button(0, 0);
blackbutton[1] = new Button(0, 2);
}
}
这是我的主文件的基本信息。
我已经尝试algandmed();
和algandmed a = new algandmed();
来调用我的主文件中的代码,但是我不知道为什么,如果有人解释了原因,我会感激不尽那些不会起作用的东西会起作用。
主要
package harjutamine;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Checkerboard extends JPanel implements ActionListener {
public void drawFrame(Graphics g, int frameNumber, int width, int height) {
int row; // Row number, from 0 to 7
int col; // Column number, from 0 to 7
int x, y; // Top-left corner of square
for (row = 0; row < 8; row++) {
//Kabelaud
for (col = 0; col < 8; col++) {
x = col * 50;
y = row * 50;
if ((row % 2) == (col % 2)) {
g.setColor(Color.BLACK);
} else {
g.setColor(Color.WHITE);
}
g.fillRect(x, y, 50, 50);
}
}
//This is where I try to call the function, but it doesn't work
algandmed aa = new algandmed();
for (Button n: (whitebutton)) {
x = n.col * 50 + 4;
y = n.row * 50 + 4;
g.setColor(Color.RED);
g.drawOval(x, y, 40, 40);
g.fillOval(x, y, 40, 40);
}
for (Button n: (blackbutton)) {
x = n.col * 50 + 4;
y = n.row * 50 + 4;
g.setColor(Color.BLUE);
g.drawOval(x, y, 40, 40);
g.fillOval(x, y, 40, 40);
}
}
//------ Implementation details: DO NOT EXPECT TO UNDERSTAND THIS ------
public static void main(String[] args) {
JFrame window = new JFrame("Checkerboard");
Checkerboard drawingArea = new Checkerboard();
drawingArea.setBackground(Color.WHITE);
window.setContentPane(drawingArea);
drawingArea.setPreferredSize(new Dimension(390, 390));
window.pack();
window.setLocation(100, 50);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false); // The user can't change the size.
Timer frameTimer = new Timer(20, drawingArea);
window.setVisible(true);
//frameTimer.start(); // commented out so we don't get an animation
} // end main
private int frameNum;
public void actionPerformed(ActionEvent evt) {
frameNum++;
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawFrame(g, frameNum, getWidth(), getHeight());
}
}
按钮
package harjutamine;
public class Button{
int row;
int col;
public Button(int r, int c){
row = r;
col = c;
}
}
答案 0 :(得分:0)
我想你要说的是你的代码不能编译。 drawFrame方法中没有可变白色按钮的声明。因此,编译器不会编译您的代码。如果你只是粘贴代码algandmed然后你有一个whitebutton声明。然而,这可能不是你想要的。想想哪个类应该拥有/拥有Button Arrays。如果您决定将它们放在alganmed类中,则需要提供正确的变量声明。aa.whitebutton
应该有效,因为您创建了一个名为aa的alganmed实例。由于您位于同一个包中,而whitebutton是默认可见性,因此您可以直接从main方法访问它。但请注意,这不是一个好习惯。您不应直接访问其他类内部数据。试着想一下封装alganmed数据的方法。