0

Здравствуйте! Пишу игру, добавляю 2 картинку в JFrame - подставка, картошка. Всегда отображается по разному. То ли только картошка, то ли только подставка.

Как исправить,чтобы отображалось все вместе? И еще мне нужно где-то вызвать this.repaint() но я не понимаю где. Код ниже.

Game

public class Game { // главный класс
    public static void main(String[] args) throws IOException {
        JFrame frame = new JFrame("GetFruit");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setSize(700,500);
        frame.setResizable(false);
        Stand stand = new Stand();
        KeyboardObserver observer = new KeyboardObserver(stand);
        frame.addKeyListener(observer);
        frame.add(stand);
        Potato potato = new Potato();
        frame.add(potato);
    }


}

Stand

public class Stand extends JPanel{ // Подставка
    private StandDirection direction;

    private BufferedImage image;

    public Stand(){
        try {
            image = ImageIO.read(new File("src\\images\\p.jpg"));
        } catch (IOException e) {
            System.out.println("Неверный путь к изображению.");
        }
    }

    public void setDirection(StandDirection direction) {
        this.repaint();
        this.direction = direction;
    }

    public StandDirection getDirection() {
        return direction;
    }

    private int x = 250;
    private int y = 350;


    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (this.getDirection() == StandDirection.LEFT) {
            x -= 25;
            if(this.x <0 ){
               x+= 25;
            }
        } else if (this.getDirection() == StandDirection.RIGHT) {
            x += 25;
            if(this.x > 495){
                x -= 25;
            }
        }
        g.drawImage(image, x, y, null);
    }
}

Potato

public class Potato extends JPanel{ // Картошка
    private BufferedImage image;

    private int x = (int)(Math.random() * 486); // генерируем случайный x
    private int y = 100;

    public Potato(){
        try {
            image = ImageIO.read(new File("src\\images\\potato.jpg"));
        } catch (IOException e) {
            System.out.println("Неверный путь к изображению.");
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image,x,y,null);
        y += 50;
        //this.repaint();
    }


}

StandDirection

public enum StandDirection { // enum со значениями
    LEFT,
    RIGHT
}

KeyboardObserver

public class KeyboardObserver extends KeyAdapter{ // Отслеживает нажатия клавиш
    private Stand stand;

    public KeyboardObserver(Stand stand) {
        this.stand = stand;
    }


    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_LEFT){
            stand.setDirection(StandDirection.LEFT);
        }else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
            stand.setDirection(StandDirection.RIGHT);
        }
    }


}
9
  • вместо KeyListener используйте KeyAdapter. метод clone не надо добавлять. пустые методы тоже уберите. 19 июн 2017 в 17:52
  • Всё зависит от того, когда вы хотите обновлять ваше изображение. Допустим если необходимо когда что то двигается, То вам необходимо передать в KeyboardObserver ваш Frame и оттуда его обновлять
    – RodGers
    20 июн 2017 в 7:16
  • @RodGers , понял,но как сделать так,чтобы отображались все картинки?
    – mrKott
    20 июн 2017 в 8:09
  • Не совсем понял какие, что есть Stend у тебя? и что должно отрисовываться
    – RodGers
    20 июн 2017 в 9:10
  • @RodGers, смотри у меня есть Stand и Potato. У них есть метод paintComponent. Он отрисовывает их в окне JFrame. Но почему-то 2 рисунка этих не отрисовывает. При разных запусках по разному. Отрисовывает либо подставку,либо картошку,а мне надо чтобы все отрисовывалось, и подставка, и картошка. Извиняюсь за речевые повторы.
    – mrKott
    20 июн 2017 в 9:14

1 ответ 1

0

Собственно вся проблема в том, что в программе, приведённой выше на JFrame рисуются 2 JPanel potato и stand. Поскольку не задано их размеров, они занимают всю область JFrame. Есть 2 выхода.

  1. рисовать на одном JPanel,
  2. регулировать размер JPanel.

Так же если рисуется на нескольких JPanel и они отрисовываются на JFrame необходимо объявлять методом revalidate() JFrame, при перемещении JPanel. Этот метод отчищает своё пространство. Я бы предложил использовать MVC паттерн и рисовать на одном JPanel. Всё что нужно отрисовать, задаётся в классе mainField. Меняя их координаты можно менять их положение

 public class Main {

    public static void main(String[] args) {
    CalculatorView theView = new CalculatorView();
    CalculatorModel theModel=new CalculatorModel();
    new CalculatorController(theView,theModel);
    }
}

public class CalculatorController {
    private CalculatorView theView;
    private CalculatorModel theModel;

    public CalculatorController(CalculatorView theView, CalculatorModel theModel) {
        this.theView=theView;
        theView.setVisible(true);
        this.theModel=theModel;
        this.theView.addCalculationListener(new CalculateListener());
    }
    class CalculateListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            int firsNumber,secondNumber=0;
            try{
                firsNumber=theView.getFirstNumber();
                secondNumber=theView.getSecondNumber();
                theModel.addTwoNumbers(firsNumber,secondNumber);
                theView.setCalcSolution(theModel.getCalculationValue());
            }
            catch (NumberFormatException ex){
                theView.displayErrorMessage("Not int");
            }
        }
    }
}

public class CalculatorModel {
    private int calculationValue;
    public void addTwoNumbers(int firstNumber, int secondNumber){
        calculationValue=firstNumber+secondNumber;
    }
    public int getCalculationValue(){
        return calculationValue;
    }
}

public class CalculatorView extends JFrame {
    private JTextField firstNumber = new JTextField(10);
    private JLabel additionLabel = new JLabel("+");
    private JTextField secondNumber = new JTextField(10);
    private JButton calculateButton = new JButton("Calculate");
    private JTextField calcSolution = new JTextField(10);

    CalculatorView() {
        MainField calcPanel = new MainField();
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setSize(600, 200);

        calcPanel.add(firstNumber);
        calcPanel.add(additionLabel);
        calcPanel.add(secondNumber);
        calcPanel.add(calculateButton);
        calcPanel.add(calcSolution);
        this.add(calcPanel);
    }

    public int getFirstNumber() {
        return Integer.parseInt(firstNumber.getText());
    }

    public int getSecondNumber() {
        return Integer.parseInt(secondNumber.getText());
    }

    public int getSolution() { return Integer.parseInt(calcSolution.getText()); }

    public void setCalcSolution(int solution) {
        calcSolution.setText(Integer.toString(solution));
    }

    void addCalculationListener(ActionListener listenForCalcButton) {
        calculateButton.addActionListener(listenForCalcButton);
    }

    void displayErrorMessage(String errorMessage) {
        JOptionPane.showMessageDialog(this, errorMessage);
    }
}

public class MainField extends JPanel {
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image,100,100,null)
        repaint();
    }
}
0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.