简体   繁体   中英

JTextField java?

My Task:

Create an application that displays a Hangman graphic for 10 steps. This graphic should be controllable via a text field and a slider (in the range 0-10) for test purposes. The text box updates the graph as soon as the value is changed and does not wait until the Enter key is pressed. If an invalid value is entered in the text field, then an error message is displayed instead of the graphic (with the method drawString text can also be "drawn"), if there should be no value there, then the graphic should remain empty.

In my program, the change of the graphics on the JSlider works fine, but the input via the text field causes no change and the check when entering an incorrect value, I tried, but then nothing is displayed. I do not understand what's wrong because the JTextField approach is the same as JSlider ...

I have put the source code of both classes down below.

First Class:

Imports, Package...

public class HangmanFrame extends JFrame{

public HangmanFrame(){

    super("Hangman");
    HangmanPanel panel = new HangmanPanel();
    JPanel mainPanel = new JPanel();
    this.add(mainPanel);
    mainPanel.setLayout(new BorderLayout());

    JTextField t = new JTextField();
    t.getDocument().addDocumentListener(new DocumentListener(){

        @Override
        public void changedUpdate(DocumentEvent arg0) {
            try{
                Integer.parseInt(t.getText());
            }
            catch(NumberFormatException ex){
                System.out.println(ex.getMessage());
            }
            panel.repaint();
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            try{
                Integer.parseInt(t.getText());
            }
            catch(NumberFormatException ex){
                System.out.println(ex.getMessage());
            }
            panel.repaint();

        }

        @Override
        public void removeUpdate(DocumentEvent arg0) {
            try{
                Integer.parseInt(t.getText());
            }
            catch(NumberFormatException ex){
                System.out.println(ex.getMessage());
            }
            panel.repaint();
        }
    });

    JSlider s = new JSlider(JSlider.HORIZONTAL, 0, 10, 0);

    s.addChangeListener(new ChangeListener(){

        @Override
        public void stateChanged(ChangeEvent arg0) {
            panel.repaint();
        }

    });

    panel.setSlider(s);
    panel.setTextField(t);
    mainPanel.add(panel, BorderLayout.CENTER);
    mainPanel.add(s, BorderLayout.PAGE_END);
    mainPanel.add(t, BorderLayout.PAGE_START);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.pack();
    this.setSize(300,500);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
}

public static void main(String[] args) {
    new HangmanFrame();
}

}

Second Class:

public class HangmanPanel extends JPanel {

    private JSlider slider;
    private JTextField field; //Height 500, Width 300

    public void paintComponent(Graphics g){
        super.paintComponent(g);

        int sliderValue = slider.getValue();
        String fieldValue = field.getText();
        //int fieldInt = Integer.parseInt(fieldValue);

        g.drawLine(0, super.getWidth() + 99, super.getHeight(), super.getWidth() + 99); 

        if(sliderValue == 0 || fieldValue.equals("0")){
            return;
        }

        g.setColor(new Color(205,133,63));
        int xArc = this.getWidth() / 20;
        int yArc = this.getHeight() - this.getHeight() / 5;
        int arcWidth = this.getWidth() / 2;
        int arcHeight = this.getHeight() / 5;

        g.fillArc(xArc, yArc, arcWidth, arcHeight, 0, 180);

        if(sliderValue == 1 || fieldValue.equals("1")){
            return;
        }

        g.setColor(Color.BLACK);
        int x1Line = xArc + arcWidth / 2;
        int x2Line = x1Line;
        int y1Line = yArc;
        int y2Line = this.getHeight() / 6;

        g.drawLine(x1Line, y1Line, x2Line, y2Line);

        if(sliderValue == 2 || fieldValue.equals("2")){
            return;
        }

        int x3Line = x1Line;
        int x4Line = x3Line + (this.getWidth() / 3) + 20;
        int y3Line = y2Line;
        int y4Line = y3Line;

        g.drawLine(x3Line, y3Line, x4Line, y4Line);

        if(sliderValue == 3 || fieldValue.equals("3")){
            return;
        }

        int x5Line = x4Line;
        int x6Line = x5Line;
        int y5Line = y4Line;
        int y6Line = y5Line + this.getWidth() / 5; // + 60

        g.drawLine(x5Line, y5Line, x6Line, y6Line);

        if(sliderValue == 4 || fieldValue.equals("4")){
            return;
        }

        g.setColor(new Color(255, 221, 204));
        g.fillOval(x6Line - this.getHeight() / 20, y6Line, this.getHeight() / 10, this.getHeight() / 10); // -25, ...,50, 50

        if(sliderValue == 5 || fieldValue.equals("5")){
            return;
        }

        g.setColor(Color.BLUE);
        g.fillOval((int) ((int) x6Line - this.getHeight() / 14.7) , (int) (y6Line + this.getHeight() / 10.41), (int)(this.getHeight() / 7.14), (int)(this.getHeight() / 4.16)); // 34, 48, 70, 120                        

        if(sliderValue == 6 || fieldValue.equals("6")){
            return;
        }

        int x7Line = x6Line + (int)(this.getHeight() / 17.85); // 28
        int x8Line = x7Line + (int)(this.getHeight() / 12.5); // 40
        int y7Line = y6Line + (int)(this.getHeight() / 7.14); // 70
        int y8Line = y7Line - (int)(this.getHeight() / 14.28); // 35

        g.setColor(Color.BLACK);
        g.drawLine(x7Line, y7Line, x8Line, y8Line);

        if(sliderValue == 7 || fieldValue.equals("7")){
            return;
        }

        int x9Line = x7Line - (int)(this.getHeight() / 9.43); // 53
        int x10Line = x9Line - (int)(this.getHeight() / 14.28); // 35
        int y9Line = y7Line;
        int y10Line = y8Line;

        g.drawLine(x9Line, y9Line, x10Line, y10Line);

        if(sliderValue == 8 || fieldValue.equals("8")){
            return;
        }

        int x11Line = x7Line;
        int x12Line = x8Line;
        int y11Line = y7Line + (int)(this.getHeight() / 6.66); // 75
        int y12Line = y8Line + (int)(this.getHeight() / 3.33); // 150

        g.drawLine(x11Line, y11Line, x12Line, y12Line);

        if(sliderValue == 9 || fieldValue.equals("9")){
            return;
        }

        int x13Line = x9Line;
        int x14Line = x10Line;
        int y13Line = y11Line;
        int y14Line = y12Line;

        g.drawLine(x13Line, y13Line, x14Line, y14Line);

    }

    public void setSlider(JSlider slider){
        this.slider = slider;
    }

    public void setTextField(JTextField field){
        this.field = field;
    }

}

Your JTextField reading works, but a problem is that you're first checking for the slider's value, and so if the slider if check is true, the method short circuits. To prove that it's working, move the slider all the way to the right, and then enter 1 or 2 into the JTextField.

If this were my project and I wanted to test this effect, I'd get all logic out of the painting method and instead allow my controllers to change a state value of the observed class, call repaint() and then draw the image based on that state.

For example, something like so:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

@SuppressWarnings("serial")
public class HangmanGUI2 extends JPanel {
    private HangmanModel model = new HangmanModel();
    private HangmanPanel2 panel2 = new HangmanPanel2(model);
    private JSlider slider = new JSlider(0, HangmanModel.MAX_VALUE, 0);
    private JTextField textField = new JTextField(10);

    public HangmanGUI2() {
        textField.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void removeUpdate(DocumentEvent e) {
                updateModel(e);
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                updateModel(e);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                updateModel(e);
            }

            private void updateModel(DocumentEvent e) {
                Document doc = e.getDocument();
                int length = doc.getLength();
                try {
                    String text = doc.getText(0, length);
                    int value = Integer.parseInt(text.trim());
                    setModelValue(value);
                } catch (BadLocationException e1) {
                    e1.printStackTrace();
                } catch (NumberFormatException e1) {
                    // Do Nothing
                }
            }
        });

        slider.setMajorTickSpacing(1);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.addChangeListener(e -> {
            int value = slider.getValue();
            setModelValue(value);
        });

        setLayout(new BorderLayout());
        add(panel2);
        add(textField, BorderLayout.PAGE_START);
        add(slider, BorderLayout.PAGE_END);

//        new Timer(1000, e -> {
//            model.increment();
//            repaint();
//        }).start();  
    }

    protected void setModelValue(int value) {
        model.setValue(value);
        repaint();
    }

    private static void createAndShowGui() {
        HangmanGUI2 mainPanel = new HangmanGUI2();

        JFrame frame = new JFrame("HangmanGUI2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

class HangmanModel {
    public static final int MAX_VALUE = 9;
    private int value = 0;

    public int getValue() {
        return value;
    }

    public void increment() {
        setValue(getValue() + 1);
    }

    public void setValue(int value) {
        this.value = Math.min(value, MAX_VALUE);
        this.value = Math.max(this.value, 0);
    }    

}

@SuppressWarnings("serial")
class HangmanPanel2 extends JPanel {
    private HangmanModel model;
    private List<Image> images = ImageCreator.getImages();

    public HangmanPanel2(HangmanModel model) {
        this.model = model;
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet() || images.size() == 0) {
            return super.getPreferredSize();
        }
        int w = images.get(0).getWidth(this);
        int h = images.get(0).getHeight(this);
        return new Dimension(w, h);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(images.get(model.getValue()), 0, 0, this);
    }
}

class ImageCreator {
    private static final int W = 284;
    private static final int H = 425;
    private static final Color BASE_COLOR = new Color(205, 133, 63);

    public static List<Image> getImages() {
        List<Image> images = new ArrayList<>();
        BufferedImage img = new BufferedImage(W, H, BufferedImage.TYPE_INT_ARGB);
        images.add(createImageCopy(img));
        Graphics2D g2 = img.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2.setColor(BASE_COLOR);
        int xArc = W / 20;
        int yArc = H - H / 5;
        int arcWidth = W / 2;
        int arcHeight = H / 5;

        g2.fillArc(xArc, yArc, arcWidth, arcHeight, 0, 180);


        images.add(createImageCopy(img));

        // -----------------------------------------

        g2.setColor(Color.BLACK);
        int x1Line = xArc + arcWidth / 2;
        int x2Line = x1Line;
        int y1Line = yArc;
        int y2Line = H / 6;

        g2.drawLine(x1Line, y1Line, x2Line, y2Line);

        images.add(createImageCopy(img));

        // -----------------------------------------

        int x3Line = x1Line;
        int x4Line = x3Line + (W / 3) + 20;
        int y3Line = y2Line;
        int y4Line = y3Line;

        g2.drawLine(x3Line, y3Line, x4Line, y4Line);

        images.add(createImageCopy(img));

        // -----------------------------------------

        int x5Line = x4Line;
        int x6Line = x5Line;
        int y5Line = y4Line;
        int y6Line = y5Line + W / 5; // + 60

        g2.drawLine(x5Line, y5Line, x6Line, y6Line);

        // -----------------------------------------

        g2.setColor(new Color(255, 221, 204));
        g2.fillOval(x6Line - H / 20, y6Line, H / 10,
                H / 10); // -25, ...,50, 50

        images.add(createImageCopy(img));

        // -----------------------------------------

        g2.setColor(Color.BLUE);
        g2.fillOval((int) ((int) x6Line - H / 14.7),
                (int) (y6Line + H / 10.41), (int) (H / 7.14),
                (int) (H / 4.16)); // 34, 48, 70, 120

        images.add(createImageCopy(img));

        // -----------------------------------------

        int x7Line = x6Line + (int) (H / 17.85); // 28
        int x8Line = x7Line + (int) (H / 12.5); // 40
        int y7Line = y6Line + (int) (H / 7.14); // 70
        int y8Line = y7Line - (int) (H / 14.28); // 35

        g2.setColor(Color.BLACK);
        g2.drawLine(x7Line, y7Line, x8Line, y8Line);

        images.add(createImageCopy(img));

        // -----------------------------------------

        int x9Line = x7Line - (int) (H / 9.43); // 53
        int x10Line = x9Line - (int) (H / 14.28); // 35
        int y9Line = y7Line;
        int y10Line = y8Line;

        g2.drawLine(x9Line, y9Line, x10Line, y10Line);

        images.add(createImageCopy(img));

        // -----------------------------------------

        int x11Line = x7Line;
        int x12Line = x8Line;
        int y11Line = y7Line + (int) (H / 6.66); // 75
        int y12Line = y8Line + (int) (H / 3.33); // 150

        g2.drawLine(x11Line, y11Line, x12Line, y12Line);

        images.add(createImageCopy(img));

        // -----------------------------------------

        int x13Line = x9Line;
        int x14Line = x10Line;
        int y13Line = y11Line;
        int y14Line = y12Line;

        g2.drawLine(x13Line, y13Line, x14Line, y14Line);
        images.add(createImageCopy(img));

        g2.dispose();
        return images;
    }

    private static Image createImageCopy(BufferedImage img) {
        int w = img.getWidth();
        int h = img.getHeight();
        BufferedImage img2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        Graphics g = img2.getGraphics();
        g.drawImage(img, 0, 0, null);
        g.dispose();
        return img2;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM