Getter Setter не даст переменную - PullRequest
0 голосов
/ 22 февраля 2020

поэтому я хотел запрограммировать tictactoe, и когда я создавал геттеры и сеттеры, они не возвращали мне переменную. И я посмотрел, что может быть не так в них, но я не нашел ошибку. Я надеюсь, что кто-то может объяснить мне, что не так. Это просто настройка панели, ее возврат, настройка строки и ее возврат. Я новичок в программировании и был бы признателен, если бы кто-то мог помочь мне с этой проблемой.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 * @author Anid Memisi
 *
 * @date 21.02.2020
 *
 * @version 1.0
 */

public class TicTacToe {

    public void tictactoe() {
        //basic constructor
            TicTacToe t = new TicTacToe();
            t.GridLayout();
        }

    public void Entscheid() {
        TicTacToe t = new TicTacToe();
        t.Update();
    }

    public void Update() {
        Setter_and_Getter s = new Setter_and_Getter();
        String feldI=s.getFeldi();
        JPanel panel=s.getPanel();
        System.out.print(feldI);
        System.out.print(panel);
        String[] feld = new String[] {" "," "," "," "," "," "," "," "," "};
        feld[0] = feldI;
        System.out.print(feldI);
        if(!feldI.equals(" ")){
            if(panel != null) {
                panel.removeAll();
                panel.invalidate();
                panel.repaint();
            }
            panel.setLayout(new GridLayout(3, 3));
            //creates the tiles for the tictactoe
            JButton button1 = new JButton(feld[0]);
            JButton button2 = new JButton(feld[1]);
            JButton button3 = new JButton(feld[2]);
            JButton button4 = new JButton(feld[3]);
            JButton  button5 = new JButton(feld[4]);
            JButton button6 = new JButton(feld[5]);
            JButton button7 = new JButton(feld[6]);
            JButton  button8 = new JButton(feld[7]);
            JButton button9 = new JButton(feld[8]);
            panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            panel.add(button1);
            panel.add(button2);
            panel.add(button3);
            panel.add(button4);
            panel.add(button5);
            panel.add(button6);
            panel.add(button7);
            panel.add(button8);
            panel.add(button9);
            panel.revalidate();
            panel.repaint();
            panel.requestFocus();
        }
    }

    public void GridLayout() {
        TicTacToe t = new TicTacToe();
        Setter_and_Getter s = new Setter_and_Getter();

        String[] feld = new String[] {" "," "," "," "," "," "," "," "," "};

        JFrame frame = new JFrame("Grid Layout");
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600,600);
        JPanel panel = new JPanel();
        //creates the tiles for the tictactoe
        panel.setLayout(new GridLayout(3,3));
        JButton button1 = new JButton(feld[0]);
        JButton button2 = new JButton(feld[1]);
        JButton button3 = new JButton(feld[2]);
        JButton button4 = new JButton(feld[3]);
        JButton button5 = new JButton(feld[4]);
        JButton button6 = new JButton(feld[5]);
        JButton button7 = new JButton(feld[6]);
        JButton button8 = new JButton(feld[7]);
        JButton button9 = new JButton(feld[8]);
        panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        panel.add(button1);
        panel.add(button2);
        panel.add(button3);
        panel.add(button4);
        panel.add(button5);
        panel.add(button6);
        panel.add(button7);
        panel.add(button8);
        panel.add(button9);
        frame.add(panel);

        s.setPanel(panel);


        //sends the input to the listener
        DerHandler handler = new DerHandler();
        button1.addActionListener(handler);

        DerHandler2 handler2 = new DerHandler2();
        button2.addActionListener(handler2);

        DerHandler3 handler3 = new DerHandler3();
        button3.addActionListener(handler3);

        DerHandler4 handler4 = new DerHandler4();
        button4.addActionListener(handler4);

        DerHandler5 handler5 = new DerHandler5();
        button5.addActionListener(handler5);

        DerHandler6 handler6 = new DerHandler6();
        button6.addActionListener(handler6);

        DerHandler7 handler7 = new DerHandler7();
        button7.addActionListener(handler7);

        DerHandler8 handler8 = new DerHandler8();
        button8.addActionListener(handler8);

        DerHandler9 handler9 = new DerHandler9();
        button9.addActionListener(handler9);
        }
 private class DerHandler implements ActionListener {

     @Override
     public void actionPerformed(ActionEvent e) {
         TicTacToe t = new TicTacToe();
         Setter_and_Getter s = new Setter_and_Getter();
         String feldI =" ";
         //gets the text of the tile
         Object source = e.getSource();
         //compares it
         if (source instanceof JButton) {
             feldI = "1";
         }
         s.setFeldI(feldI);
         System.out.print(feldI);
         t.Entscheid();
     }
 }

    private class DerHandler2 implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            TicTacToe t = new TicTacToe();
            Setter_and_Getter s = new Setter_and_Getter();
            String feldI =" ";
            //gets the text of the tile
            Object source = e.getSource();
            //compares it
            if (source instanceof JButton) {
                feldI = "2";
            }
            s.setFeldI(feldI);
            System.out.print(feldI);
            t.Entscheid();
        }
    }
    private class DerHandler3 implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            TicTacToe t = new TicTacToe();
            Setter_and_Getter s = new Setter_and_Getter();
            String feldI =" ";
            //gets the text of the tile
            Object source = e.getSource();
            //compares it
            if (source instanceof JButton) {
                feldI = "3";
            }
            s.setFeldI(feldI);
            System.out.print(feldI);
            t.Entscheid();
        }
    }
    private class DerHandler4 implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            TicTacToe t = new TicTacToe();
            Setter_and_Getter s = new Setter_and_Getter();
            String feldI =" ";
            //gets the text of the tile
            Object source = e.getSource();
            //compares it
            if (source instanceof JButton) {
                feldI = "4";
            }
            s.setFeldI(feldI);
            System.out.print(feldI);
            t.Entscheid();
        }
    }
    private class DerHandler5 implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            TicTacToe t = new TicTacToe();
            Setter_and_Getter s = new Setter_and_Getter();
            String feldI =" ";
            //gets the text of the tile
            Object source = e.getSource();
            //compares it
            if (source instanceof JButton) {
                feldI = "5";
            }
            s.setFeldI(feldI);
            System.out.print(feldI);
            t.Entscheid();
        }
    }
    private class DerHandler6 implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            TicTacToe t = new TicTacToe();
            Setter_and_Getter s = new Setter_and_Getter();
            String feldI =" ";
            //gets the text of the tile
            Object source = e.getSource();
            //compares it
            if (source instanceof JButton) {
                feldI = "6";
            }
            s.setFeldI(feldI);
            System.out.print(feldI);
            t.Entscheid();
        }
    }
    private class DerHandler7 implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            TicTacToe t = new TicTacToe();
            Setter_and_Getter s = new Setter_and_Getter();
            String feldI =" ";
            //gets the text of the tile
            Object source = e.getSource();
            //compares it
            if (source instanceof JButton) {
                feldI = "7";
            }
            s.setFeldI(feldI);
            System.out.print(feldI);
            t.Entscheid();
        }
    }
    private class DerHandler8 implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            TicTacToe t = new TicTacToe();
            Setter_and_Getter s = new Setter_and_Getter();
            String feldI =" ";
            //gets the text of the tile
            Object source = e.getSource();
            //compares it
            if (source instanceof JButton) {
                feldI = "8";
            }
            s.setFeldI(feldI);
            System.out.print(feldI);
            t.Entscheid();
        }
    }
    private class DerHandler9 implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            TicTacToe t = new TicTacToe();
            Setter_and_Getter s = new Setter_and_Getter();
            String feldI =" ";
            //gets the text of the tile
            Object source = e.getSource();
            //compares it
            if (source instanceof JButton) {
                feldI = "9";
            }
            s.setFeldI(feldI);
            System.out.print(feldI);
            t.Entscheid();
        }
    }

public static void main(String[] args) {
    TicTacToe t = new TicTacToe();
        t.tictactoe();
        }
}
import javax.swing.*;

public class Setter_and_Getter {

    private String feldI;
    private JPanel panel;

    public void setFeldI(String feldI){
        this.feldI=feldI;
    }

    public void setPanel(JPanel panel){
        this.panel=panel;
    }

    public String getFeldi(){
        return this.feldI;
    }

    public JPanel getPanel(){
        return this.panel;
    }
}

1 Ответ

0 голосов
/ 22 февраля 2020

В каждом методе actionPerformed () вы создаете новый экземпляр Setter_and_Getter и устанавливаете значение. В конце этих методов область действия метода заканчивается, поэтому объект Setter_and_Getter удаляется сборщиком мусора.

Таким образом, нет способа получить доступ к этим экземплярам объекта позже.

В вашем методе Update () вы снова создаете новый экземпляр Setter_and_Getter и считывает два значения. Получатели возвращают ноль, потому что значения действительно нулевые. Вы не вызывали никакой установщик этого экземпляра объекта раньше.

Вам нужно хранить экземпляры объекта где-то за пределами ваших методов, а затем читать из ранее заполненного экземпляра вместо чтения нового пустого экземпляра fre sh.

Кстати: вы должны использовать имена в нижнем регистре для всех методов класса TicTacToe. Имена в верхнем регистре обозначают имя класса по соглашению.

...