代码之家  ›  专栏  ›  技术社区  ›  Dominick

按jbutton java更改图像

  •  0
  • Dominick  · 技术社区  · 7 年前

    您好,我的代码有问题,几天来我一直在试图找出问题所在,并查看了一些相关的程序以寻求帮助,但无法找到答案。该程序应该根据你按下的按钮改变交通灯的图像:红色、黄色或绿色。有3节课。我正在eclipse中运行该程序。 包含主要方法的1类交通灯:

    import javax.swing.*;
    import java.awt.*;
    public class trafficLight
    {
       //-----------------------------------------------------------------
       //  Creates and displays the main program frame.
       //-----------------------------------------------------------------
       public static void main(String[] args)
       {
          JFrame frame = new JFrame("CHANGE TRAFFIC LIGHT");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
          trafficLightPanel lights = new trafficLightPanel();
          trafficLightControls controls = new trafficLightControls(lights);
    
          JPanel panel = new JPanel();
          panel.setBackground(Color.blue);
          panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    
    
    
          panel.add(Box.createRigidArea (new Dimension (0, 20)));
          panel.add(lights);
          panel.add(Box.createRigidArea (new Dimension (0, 10)));
          panel.add(controls);
          panel.add(Box.createRigidArea (new Dimension (0, 10)));
    
          frame.getContentPane().add(panel);
          frame.pack();
          frame.setVisible(true);
       }
    }
    

    第二类trafficLightPanel包含imageicons部分:

    import java.awt.*;
    import javax.swing.*;
    public class trafficLightPanel extends JPanel
    {
        public int count, redCount, yellowCount, greenCount;
        private ImageIcon none, red, yellow, green;
        private JLabel imageLabel;
        //-----------------------------------------------------------------
        // Constructor: Sets up the images and the initial state.
        //-----------------------------------------------------------------
        public trafficLightPanel()
        {
    
            none = new ImageIcon("nonePic.png");
            red = new ImageIcon("redPic.png");
            yellow = new ImageIcon("yellowPic.png");
            green = new ImageIcon("greenPic.png");
            setBackground(Color.black);
            redCount = 1; yellowCount = 2; greenCount = 3;
    
            imageLabel = new JLabel(none);
    
            add(imageLabel);
    
        }
        //-----------------------------------------------------------------
        // Paints the panel using the appropriate image.
        //-----------------------------------------------------------------
        public void paintComponent(Graphics page)
        {
            super.paintComponent(page);
    
            if (count == redCount)
            {
                imageLabel.setIcon(red);
            }
            if (count == yellowCount)
            {
                imageLabel.setIcon(yellow);
            }
            if (count == greenCount)
            {
                imageLabel.setIcon(green);
            }
        }
        //-----------------------------------------------------------------
        // Sets the status of the traffic light.
        //-----------------------------------------------------------------
        public void setCount(int newCount)
        {
             count = newCount;
        }
    }
    

    包含JButton的三级TrafficLightControl:

    //********************************************************************
    // Represents the control panel for the traffic light program.
    //********************************************************************
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class trafficLightControls extends JPanel
    {
        private trafficLightPanel lights;
        private JButton red, yellow, green;
        //-----------------------------------------------------------------
        // Sets up the traffic light control panel.
        //-----------------------------------------------------------------
        public trafficLightControls(trafficLightPanel lightPanel)
        {
                lights = lightPanel;
                red = new JButton("RED");
                red.addActionListener(new redListener());
                yellow = new JButton("YELLOW");
                yellow.addActionListener(new yellowListener());
                green = new JButton("GREEN");
                green.addActionListener(new greenListener());
    
                setBackground(Color.black);
                add(red);
                add(yellow);
                add(green);
    
        }
        //*****************************************************************
        // Represents the listener for the red button.
        //*****************************************************************
        private class redListener implements ActionListener
        {
            //--------------------------------------------------------------
            // sets count to redCount and repaints the lights panel.
            //--------------------------------------------------------------
            public void actionPerformed(ActionEvent event)
            {
                lights.setCount(lights.redCount);
                lights.repaint();
            }
        }
        //*****************************************************************
        //Represents the listener for the yellow button.
        //*****************************************************************
        private class yellowListener implements ActionListener
        {
            //--------------------------------------------------------------
            //sets count to yellowCount and repaints the lights panel.
            //--------------------------------------------------------------
            public void actionPerformed(ActionEvent event)
            {
                lights.setCount(lights.yellowCount);
                lights.repaint();
            }
        }
        //*****************************************************************
        //Represents the listener for the green button.
        //*****************************************************************
        private class greenListener implements ActionListener
        {
            //--------------------------------------------------------------
            //sets count to green count and repaints the lights panel.
            //--------------------------------------------------------------
            public void actionPerformed(ActionEvent event)
            {
                lights.setCount(lights.greenCount);
                lights.repaint();
            }
        }
    }
    

    nonePic.png the non lit up traffic light image redPic.png of traffic light lit up with red yellowPic.png greenPic.png

    每次我点击一个按钮,它都应该将trafficLightPanel对象lights中的计数设置为与颜色对应的计数,然后根据该计数,图像应该被相应的图像替换。所有组件都以方框布局放在一起。

    出于某种原因,只有红色会起作用。。。它开始显示非图片,一个没有任何灯光,当我点击红色它显示红色图片。如果我在单击红色按钮之前或之后单击任何按钮,则不会显示其他按钮。如果我先单击其他按钮中的一个,然后单击红色按钮,出于某种原因,红色仍然可以显示。所有图像都在根文件夹中(这是正确的名称吗?),包含src和bin文件夹的文件夹。

    我认为计数可能有问题,我试着做了一些事情,比如添加一个jLabel,它每次都会用方框布局将计数显示到程序中,但它不会显示任何内容(这一尝试不在代码中)。我还尝试将jLabel放入trafficLightControls类,并将其与add(红色)add(黄色)一起添加。。。。但它不会显示任何内容。我尝试的另一件事是每次都将按钮的文本更改为显示带有计数的颜色,以替代jLabel尝试。我试过使用。setText(“”)方法类似于红色。red的侦听器类中的setText(“”)。如果有人能解释如何添加jLabel并更改按钮的文本,我将不胜感激,正如我在这一特定的小段落中所描述的那样,因为这是我想知道如何做的事情,以供将来参考,尽管没有必要解决我的问题,所以可以不帮助解决这一小段落。

    非常感谢任何人提供的任何帮助!

    编辑:(很抱歉,我留下了我试图制作jLabels来测试代码的残余部分,但我删除了它们,虽然它们没有影响我相信的代码,但我试图使用它们是因为我的问题。如果这让任何人感到困惑,我很抱歉)

    1 回复  |  直到 7 年前
        1
  •  1
  •   Hovercraft Full Of Eels    7 年前

    没有必要打电话 repaint() 你不应该无视 paintComponent 如果你所做的只是交换图像图标。只需呼叫 setIcon(...) 在你的JLabel上就是所需要的一切。模型将触发视图本身的重新绘制。

    摆脱paintComponent覆盖并将setCount更改为如此简单的操作:

    public void setCount(int newCount) {
        count = newCount;
        Icon icon = null;
        switch (count) {
        case 1:
            icon = red;
            break;
        case 2:
            icon = yellow;
            break;
        case 3: 
            icon = green;
            break;
        default:
            icon = null;
            break;
        }
        imageLabel.setIcon(icon);
    }
    

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.util.EnumMap;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class Traff2 extends JPanel {
        public Traff2() {
            Traff2LightPanel lightPanel = new Traff2LightPanel();
            Traff2LightControlsPanel controlsPanel = new Traff2LightControlsPanel(lightPanel);
    
            setLayout(new BorderLayout());
            add(lightPanel, BorderLayout.CENTER);
            add(controlsPanel, BorderLayout.PAGE_END);
        }
    
        private static void createAndShowGui() {
            Traff2 mainPanel = new Traff2();
    
            JFrame frame = new JFrame("Traffic");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    }
    

    enum Light {
        NONE(""), RED("Red"), YELLOW("Yellow"), GREEN("Green");
    
        private String text;
    
        private Light(String text) {
            this.text = text;
        }
    
        public String getText() {
            return text;
        }
    }
    

    @SuppressWarnings("serial")
    class Traff2LightPanel extends JPanel {
        private Map<Light, Icon> lightColorMap = new EnumMap<>(Light.class);
        private JLabel imageLabel = new JLabel();
        private Light light = Light.NONE;
    
        public Traff2LightPanel() {
            // fill the map
            lightColorMap.put(Light.NONE, new ImageIcon("nonePic.png"));
            lightColorMap.put(Light.RED, new ImageIcon("redPic.png"));
            lightColorMap.put(Light.YELLOW, new ImageIcon("yellowPic.png"));
            lightColorMap.put(Light.GREEN, new ImageIcon("greenPic.png"));
    
            imageLabel.setIcon(lightColorMap.get(Light.NONE));
            add(imageLabel);
        }
    
        // when changing the light field, 
        // also set the ImageIcon
        public void setLight(Light light) {
            this.light = light;
            imageLabel.setIcon(lightColorMap.get(light));
        }
    
        public Light getLight() {
            return light;
        }
    }
    

    @SuppressWarnings("serial")
    class Traff2LightControlsPanel extends JPanel {
        private Traff2LightPanel lightPanel;
    
        public Traff2LightControlsPanel(Traff2LightPanel lightPanel) {
            this.lightPanel = lightPanel;
            for (Light light : Light.values()) {
                if (light == Light.NONE) {
                    continue;
                }
                add(new JButton(new LightAction(light)));
            }
        }
    
        // use an AbstractAction... 
        // like an ActionListener on "steroids"
        private class LightAction extends AbstractAction {
            private Light light;
    
            public LightAction(Light light) {
                super(light.getText());
                this.light = light;
            }
    
            @Override
            public void actionPerformed(ActionEvent e) {
                lightPanel.setLight(light);
            }
        }    
    }