int int 변경시 하나의 JPanel에서 마우스를 누르면 int 값이 업데이트되지 않음

StackOverflow https://stackoverflow.com//questions/20015101

문제

나는 그리드에 벽돌을 인쇄하기 위해 응용 프로그램을 코딩하고 이상적으로 색상을 변경하기 위해 메뉴 선택이 Bricks 클래스의 색을 설정하는 INT를 변경합니다.

두 개의 패널, 그리드 (사물이 그려집니다) 및 메뉴 바용 하나는 하나입니다.그리드의 숫자를 수동으로 변경하면 작동합니다. 그래서 메뉴에 문제가있을 것 같지만 확실하지 않습니다.나는 그것이 변경 될 때마다 메뉴 jpanel 메뉴에서 그리드 jpanel로 int를 어떻게 얻을 수 있는지 궁금합니다.

이것은 메뉴 코드입니다.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Selector extends JPanel implements Common, ActionListener{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public Color colorValues[] = {Color.BLACK, Color.YELLOW, Color.RED, Color.ORANGE};
    public String colors[] = {"Black", "Yellow", "Red", "Orange"};
    public JMenuItem colorItems[];
    public int display;

    //constructor
    public Selector(){
        //set size and layout
        setPreferredSize(new Dimension(SELECTOR_WIDTH, SELECTOR_HEIGHT));
        setLayout(new BorderLayout());

        //menu bar
        JMenuBar bar = new JMenuBar();
        Font f = new Font("Helvetica", Font.BOLD, 15);

        //menus
        JMenu colorMenu = new JMenu("Colour");

        //create Color menu
        String colors[] = {"Black", "Yellow", "Red", "Orange"};
        colorItems = new JMenuItem[colors.length];

        for (int i = 0; i<colors.length; i++){
            colorItems [i] = new JMenuItem(colors[i]);
            colorMenu.add(colorItems[i]);
            colorItems[i].addActionListener(this);
        }// end of for loop


        //set all font the same
        UIManager.put("Menu.font", f);
        UIManager.put("MenuBar.font", f);
        UIManager.put("MenuItem.font", f);

        //add menus
        bar.add(colorMenu);

        //add menu bar
        add(bar, BorderLayout.PAGE_START);

    }//constructor end

    public void actionPerformed(ActionEvent e){

        if (e.getSource()==colorItems[0]){
            display=0;
        }
        else if (e.getSource()==colorItems[1]){
            display=1;
        }
        else if (e.getSource()==colorItems[2]){
            display=2;
        }
        else if (e.getSource()==colorItems[3]){
            display=3;
        }
    }
}//class end
.

이것은지도 그리드 코드입니다.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MapGrid extends JPanel implements Common, MouseListener{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    //brick array
    public Bricks [] brick = new Bricks[COLUMN*ROW];

    //number array to save
    public int [] cell = new int[COLUMN*ROW];

    //coordinate variables
    private int x=0;
    private int y=0;

    Selector s = new Selector();

    //constructor
    public MapGrid(){
        //sets size, layout, and background colour
        setPreferredSize(new Dimension(MAPGRID_WIDTH, MAPGRID_HEIGHT));
        setLayout(new GridLayout(ROW, COLUMN));

        addMouseListener(this);

        //draws grid of bricks
        for (int i = 0; i <COLUMN*ROW; i++){
            cell[i] = 4;
            if ((i%COLUMN==0)&&(i>COLUMN-1)){
                x=0;
                y+=22;
            }
            brick[i] = new Bricks(x,y);
            x+=40;
        }
    }//constructor end

    //draws bricks
    public void paint(Graphics g){
        super.paint(g);
        for (int i = 0; i <COLUMN*ROW; i++){
            brick[i].draw(g);
        }
    }//paint end

    public void mousePressed(MouseEvent evt) {
        //gets mouse  and y coordinates
        int x = evt.getX();
        int y = evt.getY();

        //gets column and row of mouse location
        int c =x/BRICK_WIDTH;
        int r =y/BRICK_HEIGHT;

        //checks if mouse is within range
        if ((c>=0&&c<=COLUMN)&&(r>=0&&r<=ROW)){
            int index = (r)*COLUMN+c; //calculates brick number

            //right click - delete brick
            if (evt.isMetaDown()) {
                brick[index].setChoice(4);
                cell[index]=4;
            }
            //left click - draws brick
            else{
                brick[index].setChoice(s.display);
                cell[index]=s.display;
            }
        }
        repaint();
    }//mousePressed end

    //unused
    public void mouseEntered(MouseEvent evt) {}  
    public void mouseExited(MouseEvent evt) {}   
    public void mouseClicked(MouseEvent evt) {}  
    public void mouseReleased(MouseEvent evt) {}
}//class end
.

이것은 벽돌 코드입니다 :

import java.awt.*;

public class Bricks implements Common{

    //variables
    public int x=0;
    public int y=0;
    public int choice=3;
    public boolean clear = true;

    //size of bricks
    private static final int width = BRICK_WIDTH;
    private static final int height = BRICK_HEIGHT;

    //constructor
    public Bricks(int x, int y){
        this.x=x;
        this.y=y;
    }//constructor end

    //draw bricks
    public void draw(Graphics g){
        //set color or blank
        switch(choice){
            case 0: g.setColor(Color.BLACK);
                break;
            case 1: g.setColor(Color.YELLOW);
                break;
            case 2: g.setColor(Color.RED);
                break;
            case 3: g.setColor(Color.ORANGE);
                break;
            case 4: clear = true;
                break;
        }

        //check if set blank
        if (clear==true){
            g.setColor(Color.BLACK);
            g.drawRect(x,y,width,height);
        }
        else{
            g.fillRect(x,y,width,height);
        }
    }//draw end

    //set choice of color
    public void setChoice (int c){
        choice=c;
        clear = false;
    }//choice end
}//class end
.

도움이 되었습니까?

해결책

문제가 있습니다 :

public class MapGrid extends JPanel implements Common, MouseListener{
    //...

    Selector s = new Selector();  // ******* HERE **********

    // ...

    public void mousePressed(MouseEvent evt) {
        // ....

            else{
                brick[index].setChoice(s.display);
                cell[index]=s.display;
            }
        // ....
    }

    //...
}
.

위의 새로운 선택기 오브젝트를 작성하고 있지만 GUI에 표시된 Selector 객체와 완전히 구별 될 수 있습니다.따라서 GUI가 보유하고 표시하는 선택기의 상태를 변경하면 위를 사용하는 선택기 객체에 반영되지 않습니다.

이 문제를 해결하려면 Selector 변수가 GUI에 표시되는 하나의 동일한 선택기를 참조하는지 확인하십시오.

e.g., 그렇게

처럼 변경하십시오.
public class MapGrid extends JPanel implements Common, MouseListener{
    //...

    Selector s = null;

    public MapGrid(Selector s) {
      this.s = s;
    }

    // .... etc....
.

및 MapGrid 개체를 만들 때 표시된 True 선택기 인스턴스에 대한 참조를 전달하십시오.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top