我正在开发一个创建和编辑填字游戏的应用程序,如果它有帮助我最后发布的代码。我目前正在尝试解决这部分代码中出现的问题。
public void componentResized(ComponentEvent e) {
// TODO Auto-generated method stub
for(int i=0; i<width; i++) {
for(int j=0; j<height; j++) {
if(e.getSource()==crosswordSquare[i][j]){
blackSquare = new ImageIcon(blackSquare.getImage().getScaledInstance(
crosswordSquare[i][j].getWidth(), crosswordSquare[i][j].getHeight(), 1));
crosswordSquare[i][j].setIcon(blackSquare);
}
}
}
}
基本上我正在尝试将JButtons的ImageIcons调整为JButtons的尺寸,以便在调整大小以补偿由于我正在使用的GridLayout而导致的尺寸变化。但是,由于两个原因,此代码的结果并不完全符合我的期望。
基本上我需要找到一种更快的方法。关于如何修改/改进它的任何想法?通过绘画方法进行更新会有什么不同吗?
public class CrosswordInterface extends JFrame
implements ComponentListener, ActionListener{
//private ArrayList<ArrayList<JButton>> squares= new ArrayList<ArrayList<JButton>>();
private JButton[][] crosswordSquare = new JButton[15][15];
private ImageIcon blackSquare = new ImageIcon(
CrosswordInterface.class.getResource("BlackSquare.png"));
private JPanel panel = new JPanel();
//stores default width and height of square array
//initial value of 15 (225 squares)
private int width = 15;
private int height = 15;
public CrosswordInterface() {
CreateCrosswordGrid();
setSize(width *blackSquare.getIconWidth(), height*blackSquare.getIconHeight());
setVisible(true);
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
private void CreateCrosswordGrid() {
panel.setLayout(new GridLayout(width, height));
for(int i=0; i<width; i++) {
for(int j=0; j<height; j++) {
JButton b = new JButton();
b.setIcon(blackSquare);
//b.setText(text);
//b.setIconTextGap()
//b.setIco;
b.setSize(blackSquare.getIconWidth(), blackSquare.getIconHeight());
crosswordSquare[i][j]=b;
crosswordSquare[i][j].addComponentListener(this);
panel.add(crosswordSquare[i][j]);
}
}
panel.setSize(width * blackSquare.getIconWidth(), height * blackSquare.getIconHeight());
setSize(height * blackSquare.getIconWidth(), width * blackSquare.getIconHeight());
//panel.set
add(panel);
}
public void actionPerformed(ActionEvent e) {
for(int i=0; i<width; i++) {
for(int j=0; j<height; j++) {
if(e.getSource()==crosswordSquare[i][j]){
}
}
}
}
public void componentHidden(ComponentEvent e) {
// TODO Auto-generated method stub
}
public void componentMoved(ComponentEvent e) {
// TODO Auto-generated method stub
}
public void componentResized(ComponentEvent e) {
// TODO Auto-generated method stub
for(int i=0; i<width; i++) {
for(int j=0; j<height; j++) {
if(e.getSource()==crosswordSquare[i][j]){
blackSquare = new ImageIcon(blackSquare.getImage().getScaledInstance(
crosswordSquare[i][j].getWidth(), crosswordSquare[i][j].getHeight(), 1));
crosswordSquare[i][j].setIcon(blackSquare);
}
}
}
}
public void componentShown(ComponentEvent e) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:1)