Как сделать видимым мой пользовательский компонент Swing? - PullRequest
3 голосов
/ 13 января 2011

Я понятия не имею, почему это не покажет. Сначала я создаю экземпляр компонента, а затем добавляю его к определенному элементу в двумерном массиве JPanel. Затем я перебираю этот массив и добавляю каждую JPanel в другой контейнер JPanel, который должен содержать все JPanel.

Затем я добавляю этот последний контейнер в окно JFrame и устанавливаю для true видимость, он должен быть виден?

public class View extends JFrame {

    Board      gameBoard;
    JFrame     gameWindow   = new JFrame("Chess");
    JPanel     gamePanel    = new JPanel();
    JPanel[][] squarePanel  = new JPanel[8][8];
    JMenuBar   gameMenu     = new JMenuBar();
    JButton    restartGame  = new JButton("Restart");
    JButton    pauseGame    = new JButton("Pause");
    JButton    log          = new JButton("Log");

    View(Board board){
        gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
        gameWindow.setSize(400, 420);
        gameWindow.getContentPane().add(gamePanel, BorderLayout.CENTER);
        gameWindow.getContentPane().add(gameMenu, BorderLayout.NORTH);
        gameMenu.add(restartGame);
        gameMenu.add(pauseGame);
        gameMenu.add(log);
        gameBoard = board;
        drawBoard(gameBoard);
        gameWindow.setResizable(false);
        gameWindow.setVisible(true);

    }

    public void drawBoard(Board board){
        for(int row = 0; row < 8; row++){
            for(int col = 0; col < 8; col++){
                Box box = new Box(board.getSquare(col, row).getColour(), col, row);
                squarePanel[col][row] = new JPanel();
                squarePanel[col][row].add(box);
            }
        }
        for(JPanel[] col : squarePanel){
            for(JPanel square : col){
                gamePanel.add(square);
            }
        }
    }
}

@SuppressWarnings("serial")
class Box extends JComponent{
    Color boxColour;
    int col, row;
    public Box(Color boxColour, int col, int row){
        this.boxColour = boxColour;
        this.col = col;
        this.row = row;
        repaint();
    }
    protected void paintComponent(Graphics drawBox){
        drawBox.setColor(boxColour);
        drawBox.drawRect(50*col, 50*row, 50, 50);
        drawBox.fillRect(50*col, 50*row, 50, 50);
    }
}

И последний вопрос. Обратите внимание, как у каждого компонента Box есть позиция, что происходит с позицией, когда я добавляю компонент в JPanel и добавляю JPanel в мой JFrame? Есть ли у него такая же позиция по отношению к другим компонентам Box?

Ответы [ 2 ]

5 голосов
/ 13 января 2011

Вместо этого я попытался расширить JPanel, в моем меню появилось маленькое серое поле размером 10x10 пикселей. По крайней мере, начало

Когда вы используете JComponent, предпочтительный размер (0, 0), поэтому вы ничего не видите.

При использовании JPanel по умолчанию используется FlowLayout, а FlowLayout имеет 5-пиксельный разрыв до / после добавления каждого компонента на панель. Поскольку вы не добавляете никаких компонентов, предпочтительный размер - это просто промежуток, поэтому вы получите размер (10, 10).

Поэтому, когда вы делаете пользовательское рисование, вам нужно переопределить метод getPreferredSize (), чтобы вернуть правильное значение для пользовательского рисования, которое вы собираетесь реализовать.

Edit:

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

public class ChessBoard extends JFrame implements MouseListener, MouseMotionListener
{
    JLayeredPane layeredPane;
    JPanel chessBoard;
    JLabel chessPiece;
    int xAdjustment;
    int yAdjustment;

    public ChessBoard()
    {
        Dimension boardSize = new Dimension(600, 600);

        //  Use a Layered Pane for this this application

        layeredPane = new JLayeredPane();
        layeredPane.setPreferredSize( boardSize );
        layeredPane.addMouseListener( this );
        layeredPane.addMouseMotionListener( this );
        getContentPane().add(layeredPane);

        //  Add a chess board to the Layered Pane

        chessBoard = new JPanel();
        chessBoard.setLayout( new GridLayout(8, 8) );
        chessBoard.setPreferredSize( boardSize );
        chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
        layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);

        //  Build the Chess Board squares

        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                JPanel square = new JPanel( new BorderLayout() );
                square.setBackground( (i + j) % 2 == 0 ? Color.red : Color.white );
                chessBoard.add( square );
            }
        }

        // Add a few pieces to the board

        ImageIcon duke = new ImageIcon("dukewavered.gif"); // add an image here

        JLabel piece = new JLabel( duke );
        JPanel panel = (JPanel)chessBoard.getComponent( 0 );
        panel.add( piece );
        piece = new JLabel( duke );
        panel = (JPanel)chessBoard.getComponent( 15 );
        panel.add( piece );
    }

    /*
    **  Add the selected chess piece to the dragging layer so it can be moved
    */
    public void mousePressed(MouseEvent e)
    {
        chessPiece = null;
        Component c =  chessBoard.findComponentAt(e.getX(), e.getY());

        if (c instanceof JPanel) return;

        Point parentLocation = c.getParent().getLocation();
        xAdjustment = parentLocation.x - e.getX();
        yAdjustment = parentLocation.y - e.getY();
        chessPiece = (JLabel)c;
        chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);

        layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
        layeredPane.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
    }

    /*
    **  Move the chess piece around
    */
    public void mouseDragged(MouseEvent me)
    {
        if (chessPiece == null) return;

        //  The drag location should be within the bounds of the chess board

        int x = me.getX() + xAdjustment;
        int xMax = layeredPane.getWidth() - chessPiece.getWidth();
        x = Math.min(x, xMax);
        x = Math.max(x, 0);

        int y = me.getY() + yAdjustment;
        int yMax = layeredPane.getHeight() - chessPiece.getHeight();
        y = Math.min(y, yMax);
        y = Math.max(y, 0);

        chessPiece.setLocation(x, y);
     }

    /*
    **  Drop the chess piece back onto the chess board
    */
    public void mouseReleased(MouseEvent e)
    {
        layeredPane.setCursor(null);

        if (chessPiece == null) return;

        //  Make sure the chess piece is no longer painted on the layered pane

        chessPiece.setVisible(false);
        layeredPane.remove(chessPiece);
        chessPiece.setVisible(true);

        //  The drop location should be within the bounds of the chess board

        int xMax = layeredPane.getWidth() - chessPiece.getWidth();
        int x = Math.min(e.getX(), xMax);
        x = Math.max(x, 0);

        int yMax = layeredPane.getHeight() - chessPiece.getHeight();
        int y = Math.min(e.getY(), yMax);
        y = Math.max(y, 0);

        Component c =  chessBoard.findComponentAt(x, y);

        if (c instanceof JLabel)
        {
            Container parent = c.getParent();
            parent.remove(0);
            parent.add( chessPiece );
            parent.validate();
        }
        else
        {
            Container parent = (Container)c;
            parent.add( chessPiece );
            parent.validate();
        }
    }

    public void mouseClicked(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}

    public static void main(String[] args)
    {
        JFrame frame = new ChessBoard();
        frame.setDefaultCloseOperation( DISPOSE_ON_CLOSE );
        frame.setResizable( false );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
     }
}
1 голос
/ 13 января 2011

В прошлом я решил эту проблему, расширив JPanel вместо JComponent. Я нашел хороший пример здесь . Вот его адаптация, которая нарисует прямоугольник:

public class Box extends JPanel {
  Color color;

  public Box (Color c, int w, int h) {
    color = color;
    setSize(w, h);
  }

  @Override
  public void paintComponent(Graphics g) {
    g.setColor(color);
    g.drawOval(0, 0, getWidth(), getHeight());
 }

 ...

Это не совсем то же самое, что и приведенный выше код, но, надеюсь, это поможет вам начать работу в правильном направлении!

Краткое примечание (исходный ответ): в приведенном выше примере View - это JFrame, который никогда не отображается. Вместо этого используется переменная класса gameWindow. Было бы неплохо сделать класс верхнего уровня видимым окном.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...