【发布时间】:2018-03-01 12:16:02
【问题描述】:
我正在尝试制作一个 20px x 20px 按钮的网格,我将其定义为“单元格”,默认为空白,没有阴影等特殊装饰,单击时会更改颜色。 (它们只是为了测试目的而显示“1”)。我创建了一个 Cell 类来定义这些按钮,给每个按钮一个 ActionListener。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Cell implements ActionListener
{
private JButton button;
private EditorPanel editorPanel;
public Cell(EditorPanel editorPanel){
button = new JButton("1'");
button.addActionListener(listener -> colorCell());
button.setPreferredSize(new Dimension(20,20));
button.setMargin(new Insets(0,0,0,0));
button.setOpaque(true);
button.setContentAreaFilled(false);
this.editorPanel = editorPanel;
}
public JButton getButton() {
return button;
}
public void colorCell()
{
button.setBackground(Color.BLACK);
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
然后在我的 EditorPanel 类中使用一组 Cell 对象(单元格)来创建这些按钮的网格,其尺寸由“col”和“row”定义。
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class EditorPanel{
public JFrame jframe;
public JPanel jpanel;
public static EditorPanel editorPanel;
public Render render;
public static final int col = 45, row = 45, tile_size=20;
public static final int panelWidth=900, panelHeight=900;
public Dimension dim;
public int coloredPixels;
public Cell[][] cells;
public void getFrame() {
editorPanel = new EditorPanel();
dim = Toolkit.getDefaultToolkit().getScreenSize();
jframe = new JFrame("Pixel Art Creator");
jframe.setVisible(true);
jframe.setSize(panelWidth+17, panelHeight+40);
jframe.setLocation(dim.width/2 - jframe.getWidth()/2, dim.height/2 - jframe.getHeight()/2);
jframe.add(render = new Render());
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel addCells()
{
cells=new Cell[row][col];
JPanel panel = new JPanel(new GridLayout(row, col));
for(int i = 0; i< row; i++){
for(int j = 0; j<col; j++){
cells[i][j] = new Cell(this);
panel.add(cells[i][j].getButton());
}
}
return panel;
}
public static void main (String[] args)
{
editorPanel = new EditorPanel();
editorPanel.getFrame();
editorPanel.addCells();
}
}
然后,我尝试在 addCells() 方法中添加尝试放入单元格数组的每个已创建 Cell 对象,并将其添加到我的 JPanel。当我运行此代码时,我没有得到任何按钮,这意味着这些按钮没有被添加到 JPanel。我该怎么办?
【问题讨论】:
标签: java swing jbutton grid-layout