Расширение класса JLabel не следует макету контейнера - PullRequest
1 голос
/ 26 марта 2019

Я пытаюсь создать приложение Sudoku в Eclipse, используя WindowBuilder.Я решил использовать JLabels в качестве клеток.У меня есть класс Cell, который расширяет JLabel и добавляет 3 поля - значение, x и y.Клетки - это места в 9 JPanels с GridLayout.

Проблема в том, что когда я добавляю ячейки в JPanels, они выглядят так, как будто они сложены друг на друга, как если бы GridLayout не работал.Когда я делаю то же самое с JLabels, они выглядят нормально.

С ячейками:

enter image description here

С JLabels:

enter image description here

Это класс Cell:

import javax.swing.JLabel;

public class Cell extends JLabel {


private static final long serialVersionUID = 1L;
private int value;
private int x;
private int y;

public Cell(int value, int x, int y) {
    super(Integer.toString(value));
    this.value = value;
    this.x = x;
    this.y = y;
}

public Cell(int value) {
    this.value = value;
}

public int getValue() {
    return value;
}

public void setValue(int value) {
    this.value = value;
}

public int getX() {
    return x;
}

public void setX(int x) {
    this.x = x;
}

public int getY() {
    return y;
}

public void setY(int y) {
    this.y = y;
}

}

Ниже приведен класс MainFrame.Я изменяю две строки в методе initialize ().Он отлично работает с

JLabel cell = new JLabel(Integer.toString(j));

, но не с

JLabel cell = new Cell(j, j, i);

Полный класс MainFrame:

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;


public class MainFrame {

private JFrame frame;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainFrame window = new MainFrame();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public MainFrame() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setResizable(false);
    frame.setBounds(100, 100, 458, 532);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new GridLayout(1, 0, 0, 0));

    JPanel mainPanel = new JPanel();
    mainPanel.setForeground(Color.WHITE);
    mainPanel.setBorder(new LineBorder(new Color(0, 0, 0), 2));
    mainPanel.setBounds(10, 61, 422, 422);
    frame.getContentPane().add(mainPanel);
    mainPanel.setLayout(new GridLayout(3, 0, 0, 0));

    JPanel[] bigSquares = new JPanel[9];

    for (int i=0; i < 9; i++) {

        bigSquares[i] = new JPanel();
        mainPanel.add(bigSquares[i]);
        bigSquares[i].setBorder(new LineBorder(new Color(0, 0, 0), 2));
        bigSquares[i].setLayout(new GridLayout(3, 0, 0, 0));


        for (int j=0; j < 9; j++) {

            JLabel cell = new Cell(j, j, i);
            //JLabel cell = new JLabel();

            cell.setBorder(new LineBorder(new Color(0, 0, 0), 1));
            cell.setVerticalAlignment(SwingConstants.CENTER);
            cell.setHorizontalAlignment(SwingConstants.CENTER);
            cell.setFont(new Font("Tahoma", Font.PLAIN, 14));

            bigSquares[i].add(cell);
        }
    }


}
}

1 Ответ

1 голос
/ 26 марта 2019

Проблема в том, что JLabel уже имеет методы getX() и getY() (на самом деле, методы относятся к JComponent. См. JavaDoc для getX () .

Оригинальные методы

Возвращает текущую координату x / y начала координат компонента

Перезаписывая getX и getY, вы фактически определяете координаты компонентов относительно его родительского контейнера.


Одним из решений было бы переименовать ваши методы в getCellX, getCellY.

Другим решением будет работа с отдельным классом Cell, который имеет значение, координаты x, y и JLabel для отображения значения.

...