전함 게임을 프로그래밍하고 if 문을 사용하여 BatShip3 클래스를 호출하면 전장 배치 용 클릭 가능한 격자가있는 두 개의 JFrames가 생성됩니다. 메서드에 두 번 코드를 구현하여 각각에 대한 새로운 변수를 생성하려고 시도했지만 잘못된 점을 파악할 수 없습니다. 게임 모드를 선택하면 두 창을 모두 생성하여 검정색 배경을 제공하지만 두 번째 창에는 모눈이 없습니다. 어떤 포인터?두 클래스의 JFrames가 하나의 클래스에 있습니다.
package batship2;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* @author William
*/
public class BatShip3 extends JFrame implements ActionListener{
public JButton buttons [][] = new JButton [100][100];
public JPanel panel;
public JButton clicks [][] = new JButton [100][100];
public JPanel canvas;
Container contentArea = getContentPane();
Container contentArea2 = getContentPane();
public void BatShip3(){
JFrame window1 = new JFrame("Window 1");{
setSize (800, 600);
setVisible (true);
setBackground (Color.black);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
GridLayout experimentLayout = new GridLayout(100, 100);
panel.setLayout (experimentLayout);
panel.setBackground(Color.black);
for(int rows = 0; rows <100 ; rows++){
for(int cols = 0; cols < 100 ; cols++){
buttons [rows][cols] = new JButton();
buttons [rows][cols].setBackground(Color.blue);
buttons [rows][cols].addActionListener(this);
panel.add(buttons [rows][cols]);
}
}
contentArea.add(panel);
window1.setContentPane(contentArea);
}
JFrame window2 = new JFrame("Window 2");{
window2.setSize (800, 600);
window2.setVisible (true);
window2.setBackground (Color.black);
window2.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
canvas = new JPanel();
GridLayout experimentLayout2 = new GridLayout(100, 100);
canvas.setLayout (experimentLayout2);
canvas.setBackground(Color.black);
for(int rows1 = 0; rows1 <100 ; rows1++){
for(int cols1 = 0; cols1 < 100 ; cols1++){
clicks [rows1][cols1] = new JButton();
clicks [rows1][cols1].setBackground(Color.blue);
clicks [rows1][cols1].addActionListener(this);
canvas.add(clicks [rows1][cols1]);
}
}
contentArea2.add(canvas);
window2.setContentPane(contentArea2);
}
}
public void actionPerformed(ActionEvent ev){
for(int rows = 0; rows < 100 ; rows++){
for(int cols = 0 ; cols < 100 ; cols++){
if(ev.getSource() == buttons [rows][cols]){
buttons[rows][cols].setBackground(Color.green);
}
}
}
for(int rows1 = 0; rows1 < 100 ; rows1++){
for(int cols1 = 0 ; cols1 < 100 ; cols1++){
if(ev.getSource() == clicks [rows1][cols1]){
clicks[rows1][cols1].setBackground(Color.green);
}
}
}
}}
포맷되지 않은 코드를 읽을 수 없습니다. 왼쪽 정렬 된 코드를 작성하지 않으셔도됩니다. 그래서 우리가 그런 방식으로 읽을 것을 기대하지 마십시오. – camickr
죄송합니다. 여기에 실제로 코드를 게시하는 방법을 알아내는 데 어려움이있었습니다. 내가 고칠거야. – user2325795