簡體   English   中英

用java2D重新繪制並擺動JPanel

[英]Repaint with java2D and swing JPanel

這是我的第一個問題,因此我希望它能滿足要求。

我在Swing中開發了一個UI,當用戶單擊單選按鈕以更改玩家數量時,該UI會更新其中心部分。 中央UI是一個JPanel,我在上面繪制(使用java2D)一些面板,並且在每個面板上顯示2個帶有信息的標簽,並為每個面板繪制一個圓圈。 首次顯示UI時,一切都很好,我看到了每個圓圈的數據。 當我想將玩家數量從2更改為6時,我繪制了6個圓圈(精細),但是沒有數據顯示。 我不知道自己在做什么錯? 為了幫助您,以下是與測試課程有關的課程。 該代碼編譯並運行。

TablePanel.java:

package table;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Stroke;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;


public class TablePanel extends JPanel implements PropertyChangeListener {

    private static final long serialVersionUID = -7554443317793549599L;
    private static final double X_GAP = 20.0;
    private static final double Y_GAP = 20.0;
    private static final int X_IGAP = 20;
    private static final int Y_IGAP = 20;
    private Map<String, Double> stacks;
    private int nbPlayers;

    private static final Map<Integer, Map<Integer, int[]>> coordinates = new HashMap<Integer, Map<Integer, int[]>>();
    private static final Map<Integer, List<Integer>> layouts = new HashMap<Integer, List<Integer>>();
    private static List<JPanel> players = new ArrayList<JPanel>();

    static {

        // 6
        Map<Integer, int[]> positions = new HashMap<Integer, int[]>();
        int[] x = new int[2];
        List<Integer> index = new ArrayList<>();

        x[0] = 160 + X_IGAP;
        x[1] = 30 + Y_IGAP;
        positions.put(0, x);
        x = new int[2];
        x[0] = 295 + X_IGAP;
        x[1] = 70 + Y_IGAP;
        positions.put(1, x);
        x = new int[2];
        x[0] = 235 + X_IGAP;
        x[1] = 110 + Y_IGAP;
        positions.put(2, x);
        x = new int[2];
        x[0] = 160 + X_IGAP;
        x[1] = 110 + Y_IGAP;
        positions.put(3, x);
        x = new int[2];
        x[0] = 85 + X_IGAP;
        x[1] = 110 + Y_IGAP;
        positions.put(4, x);
        x = new int[2];
        x[0] = 30 + X_IGAP;
        x[1] = 70 + Y_IGAP;
        positions.put(5, x);
        coordinates.put(6, positions);

        index = Arrays.asList(0, 3);
        layouts.put(index.size(), index);

        index = Arrays.asList(0, 2, 4);
        layouts.put(index.size(), index);

        index = Arrays.asList(0, 2, 3, 4);
        layouts.put(index.size(), index);

        index = Arrays.asList(0, 1, 2, 4, 5);
        layouts.put(index.size(), index);

        index = Arrays.asList(0, 1, 2, 3, 4, 5);
        layouts.put(index.size(), index);

        // 10
        positions = new HashMap<Integer, int[]>();
        x = new int[2];
        x[0] = 160 + X_IGAP;
        x[1] = 30 + Y_IGAP;
        positions.put(0, x);
        x = new int[2];
        x[0] = 220 + X_IGAP;
        x[1] = 30 + Y_IGAP;
        positions.put(1, x);
        x = new int[2];
        x[0] = 285 + X_IGAP;
        x[1] = 45 + Y_IGAP;
        positions.put(2, x);
        x = new int[2];
        x[0] = 285 + X_IGAP;
        x[1] = 100 + Y_IGAP;
        positions.put(3, x);
        x = new int[2];
        x[0] = 220 + X_IGAP;
        x[1] = 110 + Y_IGAP;
        positions.put(4, x);
        x = new int[2];
        x[0] = 160 + X_IGAP;
        x[1] = 110 + Y_IGAP;
        positions.put(5, x);
        x = new int[2];
        x[0] = 100 + X_IGAP;
        x[1] = 110 + Y_IGAP;
        positions.put(6, x);
        x = new int[2];
        x[0] = 45 + X_IGAP;
        x[1] = 100 + Y_IGAP;
        positions.put(7, x);
        x = new int[2];
        x[0] = 45 + X_IGAP;
        x[1] = 45 + Y_IGAP;
        positions.put(8, x);
        x = new int[2];
        x[0] = 100 + X_IGAP;
        x[1] = 30 + Y_IGAP;
        positions.put(9, x);
        coordinates.put(10, positions);

        index = Arrays.asList(0, 2, 3, 4, 6, 7, 8);
        layouts.put(index.size(), index);

        index = Arrays.asList(0, 2, 3, 4, 5, 6, 7, 8);
        layouts.put(index.size(), index);

        index = Arrays.asList(0, 1, 2, 3, 4, 6, 7, 8, 9);
        layouts.put(index.size(), index);

        index = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
        layouts.put(index.size(), index);
    }

    /**
     * Create the panel.
     */
    public TablePanel(Map<String, Double> stacks) {
        this.stacks = stacks;
        this.nbPlayers = stacks.size();
        setLayout(null);
        setPreferredSize(new Dimension(1280, 1024));
    }

    /**
     * Create the panel.
     * 
     */
    public TablePanel(int nbPlayers) {
        this.nbPlayers = nbPlayers;
        init(nbPlayers);
        setLayout(null);
        setPreferredSize(new Dimension(1280, 1024));
    }

    private void init(int nbPlayers) {
            stacks = new HashMap<String, Double>();
            for (int i = 0; i < nbPlayers; i++) {
                    String s = "A" + String.valueOf(i);
                    stacks.put(s, 0.0);
            }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        drawTable(g2);
                drawPlayers(g2);
    }

    private void drawPlayers(Graphics2D g2) {
        System.out.println("painting players...");
        Map<Integer, int[]> positions = null;
        PlayerPanel player = null;

        if ((nbPlayers < 7) && (nbPlayers > 1)) {
            positions = coordinates.get(6);
        }
        if ((nbPlayers < 11) && (nbPlayers > 6)) {
            positions = coordinates.get(10);
        }

        Iterator<JPanel> itPanel = players.iterator();
        JPanel current = null;
        while (itPanel.hasNext()) {
            current = itPanel.next();
            remove(current);
        }
        players.clear();

        List<Integer> indexes = layouts.get(nbPlayers);
        Iterator<Integer> it = indexes.iterator();

        for (String position : stacks.keySet()) {
                    player = new PlayerPanel(position);
                    int i = it.next();
                    player.setBounds(positions.get(i)[0] - PlayerPanel.WIDTH,
                                    positions.get(i)[1] - PlayerPanel.HEIGHT,
                                    2 * PlayerPanel.WIDTH, 2 * PlayerPanel.HEIGHT);
                    add(player);
                    players.add(player);
        }
    }

    private void drawTable(Graphics2D g2) {
        System.out.println("painting table...");
        g2.setPaint(Color.green);
        // g2.setPaint(Color.BLACK);
        // Stroke stroke = new BasicStroke(6, BasicStroke.CAP_BUTT,
        // BasicStroke.JOIN_BEVEL);
        // g2.setStroke(stroke);
        Line2D lineUp = new Line2D.Double(X_GAP + 60.0, Y_GAP + 0.0,
                X_GAP + 260.0, Y_GAP + 0.0);
        g2.draw(lineUp);
        Line2D lineDown = new Line2D.Double(X_GAP + 60.0, Y_GAP + 140.0,
                X_GAP + 260.0, Y_GAP + 140.0);
        g2.draw(lineDown);

        Arc2D leftCircle = new Arc2D.Double(X_GAP + 0.0, Y_GAP + 0.0, 140.0,
                140.0, 90.0, 180.0, Arc2D.OPEN);
        g2.fill(leftCircle);

        Arc2D rightCircle = new Arc2D.Double(X_GAP + 190.0, Y_GAP + 0.0, 140.0,
                140.0, 90.0, -180.0, Arc2D.OPEN);
        g2.fill(rightCircle);

        int x[] = new int[] { X_IGAP + 60, X_IGAP + 260, X_IGAP + 260,
                X_IGAP + 60 };
        int y[] = new int[] { Y_IGAP + 0, Y_IGAP + 0, Y_IGAP + 140,
                Y_IGAP + 140 };
        g2.fillPolygon(x, y, 4);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        Object o = evt.getNewValue();
        if (o instanceof Integer) {
            nbPlayers = (int) o;
            System.out.println("changing the number of players to: "
                    + nbPlayers);
            init(nbPlayers);
        } else {
            stacks = (Map<String, Double>) o;
            this.nbPlayers = stacks.size();
        }
        System.out.println("start to repaint...");
        repaint();
    }

    private class PlayerPanel extends JPanel {

        private static final long serialVersionUID = 2519725144140029715L;
        private JLabel labelPosition;
        private JLabel labelStack;
        private static final int WIDTH = 20;
        private static final int HEIGHT = 20;

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            drawPlayer(g2);
        }

        private void drawPlayer(Graphics2D g2) {
            System.out.println("starting to draw player panel");
            g2.setPaint(Color.BLACK);
            Stroke stroke = new BasicStroke(1, BasicStroke.CAP_BUTT,
                    BasicStroke.JOIN_BEVEL);
            g2.setStroke(stroke);
            Ellipse2D circle = new Ellipse2D.Double(0.0, 0.0, (double) 2
                    * WIDTH, (double) 2 * HEIGHT);
            g2.draw(circle);
            GradientPaint cyantowhite = new GradientPaint(0, 0, Color.cyan, 40,
                    40, Color.white);
            g2.setPaint(cyantowhite);
            g2.fill(circle);
        }

        public PlayerPanel(String position) {
            System.out.println("In player panel constructor with position "
                    + position);
            setLayout(new GridLayout(2, 0));
            setBackground(Color.green);
            labelPosition = new JLabel(position);
            labelPosition.setFont(new Font("Tahoma", Font.BOLD, 9));
            labelPosition.setHorizontalAlignment(SwingConstants.CENTER);
            double value = stacks.get(position);
            if (value != 0) {
                labelStack = new JLabel(String.valueOf(value));
            } else {
                labelStack = new JLabel();
            }
            labelStack.setHorizontalAlignment(SwingConstants.CENTER);
            labelStack.setFont(new Font("Tahoma", Font.PLAIN, 9));
            add(labelPosition);
            add(labelStack);
            setMinimumSize(new Dimension(2 * WIDTH, 2 * HEIGHT));
            setMaximumSize(new Dimension(2 * WIDTH, 2 * HEIGHT));
            setPreferredSize(new Dimension(2 * WIDTH, 2 * HEIGHT));
        }
    }
}

GameDefinitionPanel.java:

package table;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class GameDefinitionPanel extends JPanel {

    private static final long serialVersionUID = 3972791004390766168L;
    private final ButtonGroup buttonGroupTable = new ButtonGroup();
    private final ButtonGroup buttonGroupTree = new ButtonGroup();
    private int nbPlayers = 2;
    private TablePanel tablePanel;
    private PropertyChangeSupport pcs = new PropertyChangeSupport(this);

    /**
     * Create the panel.
     * 
     * @throws TablePositionException
     */
    public GameDefinitionPanel() {
        setLayout(new BorderLayout(0, 0));

        JPanel optionsPanel = new JPanel();
        add(optionsPanel, BorderLayout.WEST);
        optionsPanel
                .setLayout(new BoxLayout(optionsPanel, BoxLayout.PAGE_AXIS));

        JLabel labelTableSize = new JLabel("Table size:");
        optionsPanel.add(labelTableSize);

        JRadioButton rdbtnHeadsUp = new JRadioButton("Heads up");
        rdbtnHeadsUp.setActionCommand("2");
        rdbtnHeadsUp.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sizeUpdate(e);
            }
        });
        rdbtnHeadsUp.setSelected(true);
        buttonGroupTable.add(rdbtnHeadsUp);
        optionsPanel.add(rdbtnHeadsUp);

        JRadioButton rdbtnSixHanded = new JRadioButton("Six handed");
        rdbtnSixHanded.setActionCommand("6");
        rdbtnSixHanded.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sizeUpdate(e);
            }
        });
        buttonGroupTable.add(rdbtnSixHanded);
        optionsPanel.add(rdbtnSixHanded);

        JRadioButton rdbtnFullRing = new JRadioButton("Full ring");
        rdbtnFullRing.setActionCommand("10");
        rdbtnFullRing.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sizeUpdate(e);
            }
        });
        buttonGroupTable.add(rdbtnFullRing);
        optionsPanel.add(rdbtnFullRing);

        Component box = Box.createRigidArea(new Dimension(0, 10));

        optionsPanel.add(box);

        JLabel labelTree = new JLabel("Start Tree:");
        optionsPanel.add(labelTree);

        JRadioButton rdbtnPreflop = new JRadioButton("Preflop");
        rdbtnPreflop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        rdbtnPreflop.setSelected(true);
        buttonGroupTree.add(rdbtnPreflop);
        optionsPanel.add(rdbtnPreflop);

        JRadioButton rdbtnFlop = new JRadioButton("Flop");
        rdbtnFlop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        buttonGroupTree.add(rdbtnFlop);
        optionsPanel.add(rdbtnFlop);

        JRadioButton rdbtnTurn = new JRadioButton("Turn");
        rdbtnTurn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        buttonGroupTree.add(rdbtnTurn);
        optionsPanel.add(rdbtnTurn);

        JRadioButton rdbtnRiver = new JRadioButton("River");
        rdbtnRiver.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        buttonGroupTree.add(rdbtnRiver);
        optionsPanel.add(rdbtnRiver);

        tablePanel = new TablePanel(nbPlayers);
        add(tablePanel, BorderLayout.CENTER);

        addPropertyChangeListener(tablePanel);

        JPanel blindsStacksPanel = new JPanel();
        add(blindsStacksPanel, BorderLayout.SOUTH);
        blindsStacksPanel.setLayout(new BoxLayout(blindsStacksPanel,
                BoxLayout.LINE_AXIS));

        JButton blindsButton = new JButton("Blinds");
        blindsStacksPanel.add(blindsButton);

        JButton btnStacks = new JButton("Stacks");
        blindsStacksPanel.add(btnStacks);

        JButton btnTournamentData = new JButton("Tournament Data");
        blindsStacksPanel.add(btnTournamentData);

        JButton OKButton = new JButton("OK");
        blindsStacksPanel.add(OKButton);

        JPanel gameTypePanel = new JPanel();
        add(gameTypePanel, BorderLayout.NORTH);
        gameTypePanel.setLayout(new BoxLayout(gameTypePanel,
                BoxLayout.LINE_AXIS));

        JComboBox gameTypeComboBox = new JComboBox();
        gameTypePanel.add(gameTypeComboBox);
    }

    private void sizeUpdate(ActionEvent e) {
        String s = e.getActionCommand();
        int oldValue = nbPlayers;
        nbPlayers = Integer.parseInt(s);
        pcs.firePropertyChange("nbPlayers", oldValue, nbPlayers);
        repaint();
    }

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        pcs.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        pcs.removePropertyChangeListener(listener);
    }
}

GameDefinitionPanelTest.java:

package table;

import java.awt.HeadlessException;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class GameDefinitionPanelTest {

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                GameDefinitionPanelTest test = new GameDefinitionPanelTest();
                GameDefinitionPanel gamePanel;
                try {
                    UIManager.setLookAndFeel(UIManager
                            .getSystemLookAndFeelClassName());
                    gamePanel = new GameDefinitionPanel();
                    JFrame frame = new JFrame();
                    frame.getContentPane().add(gamePanel);
                    frame.addWindowListener(new java.awt.event.WindowAdapter() {
                        public void windowClosing(java.awt.event.WindowEvent e) {
                            System.exit(0);
                        }
                    });
                    frame.setSize(800, 600);
                    frame.setVisible(true);
                } catch (HeadlessException | ClassNotFoundException
                        | InstantiationException | IllegalAccessException
                        | UnsupportedLookAndFeelException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }
}

感謝幫助 !

我沒有勇氣瀏覽所有代碼,但是如果您要向jContainer添加新的JLabel(或任何其他JThings),則需要調用revalidate()來顯示它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM