我有一个JPanel创建可点击的面板网格。我正在尝试在单击面板中的特定网格时添加标签。我试图使用add方法添加代码,但没有添加任何标签。
代码:
<button onclick="myFunction()">Show Snackbar</button>
<div id="snackbar">Some text some message..</div>
<script>
function myFunction() {
var x = document.getElementById("snackbar")
x.className = "show";
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
</script>
答案 0 :(得分:0)
刚刚更改为匿名类,然后能够使用setVisible(true)。我添加了一些其他的东西,只是为了让它在我的最终工作。
public class CenterPanel extends JFrame {
static JLabel labelText = new JLabel("SCHEDULED",JLabel.CENTER);
public CenterPanel(int row, int col) {
this.setSize(row*50, col*50);
setLayout(new GridLayout(row, col));
//setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
JPanel pan = new JPanel();
pan.setEnabled(true);
pan.setBackground(Color.WHITE);
pan.setPreferredSize(new Dimension(3, 3));
pan.setBorder(BorderFactory.createLineBorder(Color.BLACK));
// an exception to not click the top row and most left column headers
if (i != 0 && j != 0) {
pan.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
pan.setBackground(Color.RED);
pan.add(new JLabel("HIT"));
setVisible(true);
}
}); // add a mouse listener to make the panels clickable
}
// set names for each panel for later use
pan.setName("PANEL_" + i + "_" + j);
add(pan);
setVisible(true);
}
}
}
}