首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JButtons的微型像素艺术程序

使用JButtons的微型像素艺术程序
EN

Stack Overflow用户
提问于 2017-04-29 20:48:48
回答 1查看 91关注 0票数 1

我最近刚进入Java,现在仍然是个菜鸟。我创建了一个9x9面板的JPanels,使用一个for循环添加按钮。如何创建一个动作侦听器,允许我选择不同的颜色,这些颜色将在单击JButton时显示为背景色?我正试着制作一个微型像素艺术程序。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-29 21:29:34

看起来会像这样。在本例中,[row][col]引用网格的行和列值。确保创建计数器(private static int counter = 0;)。否则你会犯一大堆错误。以下是守则:

代码语言:javascript
复制
JBut[row][col].addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        typeOfButton button = (typeOfButton) e.getSource();
        int row = button.getRow();
        int col = button.getCol();

        counter++;
        if (counter == 1) {
            JBut[row][col].setBackground(Color.RED);
        } 
        else if (counter == 2) {
            JBut[row][col].setBackground(Color.ORANGE);
        } 
        else if (counter == 3) {
            JBut[row][col].setBackground(Color.YELLOW);
        } 
        else if (counter == 4) {
            JBut[row][col].setBackground(Color.GREEN);
        } 
        else if (counter == 5){
            JBut[row][col].setBackground(Color.BLUE);
        } 
        else if (counter == 6){
            JBut[row][col].setBackground(Color.MAGENTA);
        } 
        else {
            JBut[row][col].setBackground(Color.BLACK);
            counter = 0; //makes color cycle repeat, starting with red
        } //end else
    } //end actionPerformed
}); //end ActionListener

显然,这样做的简单方法是将巨大的if语句放入一个名为determineColor()之类的新方法中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43700319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档