我試圖在JPanel頂部放置一個.jpg圖標,以表示板上的一塊電路板。我有一個包含.java文件的GUI文件夾和另一個包含.jpg文件的文件夾。在JPanel頂部添加JLabel
- 主要Edit-- 示例代碼
當方點擊白色圖標是爲了放置,然後黑色等等等等,這是什麼即時試圖實現
一個非常基本的例子import java.awt.Dimension;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class gui extends JFrame implements MouseListener {
/**
*
*/
private static final long serialVersionUID = -973341728129968945L;
JLayeredPane layeredPane;
JPanel board;
JLabel piece;
int numSquares;
private boolean currentPlayer;
public gui(){
Dimension boardSize = new Dimension(600, 600);
numSquares = 6;
currentPlayer = true;
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(this);
board = new JPanel();
layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
board.setLayout(new GridLayout(numSquares, numSquares));
board.setPreferredSize(boardSize);
board.setBounds(0, 0, boardSize.width, boardSize.height);
for (int i = 0; i < (numSquares * numSquares); i++) {
JPanel square = new JPanel(new BorderLayout());
square.setBorder(BorderFactory.createLineBorder(Color.black));
square.setBackground(Color.green);
board.add(square);
}
}
public static void main(String[] args) {
JFrame frame = new gui();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.pack();
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
@Override
public void mouseClicked(MouseEvent e) {
JPanel temp = (JPanel)board.findComponentAt(e.getX(), e.getY());
System.out.println(e.getX() + " " + e.getY());
if(currentPlayer){
ImageIcon white = new ImageIcon("l/Images/white.jpg");
piece = new JLabel(white);
temp.add(piece);
}
else{
ImageIcon black = new ImageIcon("/Images/black.jpg");
piece = new JLabel(black);
temp.add(piece);
}
currentPlayer = !currentPlayer;
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
}
}
我刪除了我的答案,因爲我看到你已經使用JPanels作爲電路板的單元。我認爲你可能需要創建並向我們展示一個[sscce](http://sscce.org),以便我們能夠幫助你。 –
沒有任何東西可以顯示。代碼運行時,會創建一個6乘6的黑板背景。然後,當一個cellis點擊一個令牌(白色或黑色)是爲了放置。但沒有任何反應。 – CNevin561
如果你發佈了可編譯的,可運行的代碼,我們可以更容易地研究它,理解它,修改它,並可能幫助你糾正它。由你決定。 –