java如何在没有布局管理器的情况下显示JLabel
我正在为一个最终的项目做一个游戏,我需要一个标签,它是一个大的“X”出现在JPAND的中间。我有JPanel出现,但标签不会出现,因为我没有布局管理器,但如果我使用布局管理器,我的整个项目都会改变。这是我必须做的项目,这样你就可以看到我在努力做什么Create a game that helps new mouse users improve their hand-eye coordination. Within a JFrame, display an array of 48 JPanels in a GridLayout using eight rows and six columns. Randomly display an X on one of the panels. When the user clicks the correct panel(the one displaying the X), remove the X and display it on a different panel. After the user has successfully “hit” the correct panel 10 times, display a congratulation message that includes the user’s percentage(hits divided by clicks). Save the file as JCatchTheMouse.java.
这是我的密码
package CatchTheMouse;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CatchTheMouse extends JFrame implements ActionListener, MouseListener{
final int ROWS = 8;
final int COLS = 6;
final int GAP = 2;
final int MAX_PANELS = ROWS * COLS;
int clicks;
int hits;
int percentage = 0;
int width;
int height;
int panelX;
int panelY;
int whichPanel = (int)(Math.random() * 48 + 1);
int numberOfPanels = 1;
JLabel grats = new JLabel("");
JLabel spot = new JLabel("X");
JPanel[] panel = new JPanel[MAX_PANELS];
JPanel pane = new JPanel(new GridLayout(ROWS, COLS, GAP, GAP));
Font xFont = new Font("Ariel", Font.BOLD, 30);
Font font = new Font("Ariel", Font.PLAIN, 12);
public CatchTheMouse() {
super("Catch the Mouse");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
add(spot);
spot.setFont(xFont);
add(grats);
grats.setFont(font);
add(pane);
for(int x = 0; x < MAX_PANELS; ++x) {
panel[x] = new JPanel();
pane.add(panel[x]);
panel[x].setBackground(Color.RED);
}
pane.setBackground(Color.BLACK);
panelX = panel[whichPanel].getX();
panelY = panel[whichPanel].getY();
width = panel[whichPanel].getWidth() / 2;
height = panel[whichPanel].getHeight() / 2;
spot.setBounds(panelX, panelY, width, height);
}
public void mouseClicked(MouseEvent e) {
clicks = e.getClickCount();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args) {
CatchTheMouse frame = new CatchTheMouse();
frame.setVisible(true);
}
}
# 1 楼答案
制作另一个
JPanel
并将其放置在第一个JPanel
内。将JLabel
和Layout
添加到第二个JPanel
中,即第一个内的一个相应地设置嵌套-
JPanel
和其他坐标的位置# 2 楼答案
你的位置在所有其他面板后面。如果你加上
这将导致它被绘制在所有其他内容之上
更好的方法是在面板内部绘制x,而不是在面板顶部
编辑:
您可以使用将x添加到特定面板