当前位置: 首页 > 知识库问答 >
问题:

为什么单击按钮时会出现相同的按钮?

吕高昂
2023-03-14
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TrafficLightPanel extends JPanel implements ActionListener{
private JLabel changeColor;
private Color color;

public TrafficLightPanel(){
    setSize(new Dimension(300,200));    
    setPreferredSize (new Dimension(300, 200));
    color = color.RED;

}
public void paintComponent(Graphics g){
    g.setColor(color);
    g.fillOval(100,100,100,100);
}
public void setColor (Color shade)
{
    color = shade;
}
public void  createButton(){}
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}
public static void main(String[] args){
    JFrame frame = new JFrame("Color Circle");
    JButton[] buttons = new JButton[3];
    String[] colors = new String[]{"RED", "GREEN", "BLUE"};
    TrafficLightPanel panel = new TrafficLightPanel()
    {
        @Override
        public void  createButton(){
            for(int i = 0; i < 3; i++)
            {
                // make new button name 

                buttons[i] = new JButton("" + colors[i]);
                if(i == 0)
                    buttons[i].addActionListener(this);
                else if(i == 1)
                    buttons[i].addActionListener(this);
                else if(i == 2)
                    buttons[i].addActionListener(this);

                add(buttons[i]);
                //System.out.println(buttons[i]);
            }
        }
        @Override
        public void actionPerformed(ActionEvent e) {
               if (e.getSource() == buttons[0]) {
                   setColor(Color.RED);
                    repaint();
               } else if (e.getSource() == buttons[1]) {
                   setColor(Color.GREEN);
                    repaint();
               }
               else if (e.getSource() == buttons[2]) {
                   setColor(Color.BLUE);
                    repaint();
                   }
            }

            };
            panel.createButton();   
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


}

}

共有1个答案

狄元魁
2023-03-14

您的paintComponent方法应该首先调用super的方法,以便JPanel将完成其内部图形管理,其中包括删除所谓的“脏”像素。所以:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);  // *** add this ***
    g.setColor(color);
    g.fillOval(100, 100, 100, 100);
}

我自己,我会做一些不同的事情,有一些你可以考虑或不考虑的建议:

  • 创建一个JPanel,该JPanel只用于绘图,不用于其他操作,不用于按钮,不用于其他操作。
  • 将JButtons放置在不同的JPanel中。
  • 使用枚举,可能称为LightColor,用于将颜色与字符串组合,并在创建按钮时使用。
  • 在paintComponent方法中,将Graphics对象强制转换为Graphics2D对象,以便使用RenderingHints绘制更平滑的圆。
  • 避免设置任何大小。相反,在需要的地方重写setPreferredSize,并让应用程序的组件和布局管理器在创建JFrame后但在显示它之前通过调用pack()来调整自己的大小。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;

import javax.swing.*;

// main GUI JPanel that holds the light drawing JPanel as well as the buttons
@SuppressWarnings("serial")
public class TrafficLightPanel2 extends JPanel {
    private static final int LIGHT_SIZE = 200; // size of the circle
    private static final int GAP = 10; // border gap around the jpanel

    // the Jlight drawing JPanel that draws the circles
    private LightDrawingPanel lightDrawingPanel = new LightDrawingPanel(null, LIGHT_SIZE);

    public TrafficLightPanel2() {
        // JPanel to hold the buttons, 1 row, variable number of columns, gap between buttons
        JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
        for (LightColor lightColor : LightColor.values()) {
            // create each button within the loop, giving it an Action -- an ActionListener "on steroids"
            buttonPanel.add(new JButton(new LightColorAction(lightColor, lightDrawingPanel)));
        }

        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        setLayout(new BorderLayout(GAP, GAP));
        add(lightDrawingPanel, BorderLayout.CENTER);  // add the light drawer to the center
        add(buttonPanel, BorderLayout.PAGE_END);  // and the buttons to the bottom
    }

    private static void createAndShowGui() {
        TrafficLightPanel2 mainPanel = new TrafficLightPanel2();

        JFrame frame = new JFrame("Traffic Light");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();  // have layout managers do their thing
        frame.setLocationRelativeTo(null); // center
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

// just acts as a class that connects a Color with a String
enum LightColor {
    RED(Color.RED, "Red"), YELLOW(Color.YELLOW, "Yellow"), GREEN(Color.GREEN, "Green");

    private LightColor(Color color, String text) {
        this.color = color;
        this.text = text;
    }
    private Color color;
    private String text;

    public Color getColor() {
        return color;
    }

    public String getText() {
        return text;
    }

    @Override
    public String toString() {
        return text;
    }
}

// create a class that only draws the circle, and that's it
@SuppressWarnings("serial")
class LightDrawingPanel extends JPanel {
    private Color color;
    private int size;

    public LightDrawingPanel(Color color, int size) {
        this.color = color;
        this.size = size;
    }

    public void setColor(Color color) {
        this.color = color;
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);  // again, the super must be called

        // if no color defined, get out of here
        if (color == null) {
            return;
        }

        g.setColor(color);

        // make for smooth rendering 
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // center the circle
        int x = (getWidth() - size) / 2;
        int y = (getHeight() - size) / 2;
        g2.fillOval(x, y, size, size);
    }

    // make our JPanel at least as large as the circle
    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(size, size);
    }
}

// AbstractAction for our buttons
// like an ActionListener "on steroids"
@SuppressWarnings("serial")
class LightColorAction extends AbstractAction {
    private LightColor lightColor;
    private LightDrawingPanel lightDrawingPanel;

    public LightColorAction(LightColor lightColor, LightDrawingPanel lightDrawingPanel) {
        super(lightColor.getText());  // text for the button to show

        // initialize our fields
        this.lightColor = lightColor;
        this.lightDrawingPanel = lightDrawingPanel;

        // alt-key mnemonic derived from the text String
        int mnemonic = (int) lightColor.getText().charAt(0);
        putValue(MNEMONIC_KEY, mnemonic);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // set the color of the drawing panel
        lightDrawingPanel.setColor(lightColor.getColor());
    }
}
 类似资料:
  • 我正在使用贝宝快捷结账按钮。问题是,如果用户更改付款金额,paypal按钮将再次呈现。当我点击paypal按钮时,有没有办法渲染该按钮?我与贝宝结帐工作。js https://developer.paypal.com/docs/archive/checkout/integrate/# 更新:在web组件中工作,所以所有代码都在renderedcall back()中

  • 我的网页上的表格中有很多按钮。 每个按钮都有相同的名称,但值集不同。 当我想提取按钮值时,使用下面的按钮值不意味着我没有得到唯一的按钮值——实际单击的按钮值吗? 我怎么才能绕过它? 谢谢

  • 我能找到的每个更改按钮图像的示例都显示了当单击该按钮时如何更改它。但是我如何点击一个切换按钮,并让它改变一个常规按钮的图像呢? 关于更多细节,我有两个按钮和一个onCheckedChanged事件: 当按下切换按钮并发生onCheckedChanged事件时,我需要将btn1的背景设置为新图像。

  • 我需要在商品搜索中键入“香蕉”,然后点击“GO”按钮。 在堆栈溢出的帮助下,我可以调出火狐,输入“香蕉”...但是“Go”按钮(基于检查的Go3)不会开火!! 我试过element.click(),试过ActionChains,试过将光标移动到元素,试过验证它已经启用。它只是不会转到下一个搜索页面。 我没有得到任何错误...它只是没有进入下一页。 谢谢你能提供的任何帮助。快把我逼疯了!

  • 我有4个图像作为按钮,当选择正确的按钮时,会出现一个工作正常的箭头按钮。 我的问题是,我试图更改每个按钮的后台资源以在单击此箭头时进行更改,但我在该行得到一个空指针异常: 我已经在java onCreate中声明了nextArrow按钮- 类别: 日志: XML: 我错过了什么明显的东西吗?

  • 我在Python Selenium中出错了。我正在尝试下载所有歌曲与硒,但有一些错误。下面是代码: 下面是错误: 你知道为什么会出错吗?