我可以使用getActionCommand来改变标签内容,但是我不能用它来改变颜色? [英] I can use getActionCommand to change the label content, but I can't use it to change the color?

查看:161
本文介绍了我可以使用getActionCommand来改变标签内容,但是我不能用它来改变颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在这里的其他人的帮助下,我终于设法编写了一个按钮,交替的标签Hello World!到Hello Universe!并再次回来。我使用下面的代码,并使用相同的方式来尝试和更改颜色,但它没有按预期工作。我一直在寻找这个小时,但没有效果。感谢您阅读,任何帮助!

So with the help of others here I finally managed to code a button that alternates the label "Hello World!" to "Hello Universe!" and back again. I used the code below, and used the same way to try and change the color, but it didn't work as expected. I've been searching for hours on this, but with no avail. Thank you for reading, anything helps!

代码:

package game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Javagame extends JPanel implements ActionListener{
    protected JButton changetext;
    protected JButton red;
    protected JButton green;
    private JLabel label;

    public Javagame() {
        add(changetext = new JButton("Button!"));
        changetext.setPreferredSize(new Dimension(50, 50));
        changetext.setActionCommand("change");

        add(red = new JButton("Red"));
        red.setPreferredSize(new Dimension(50, 50));
        red.setActionCommand("changecolorRed");

        add(green = new JButton("Green"));
        green.setPreferredSize(new Dimension(50, 50));
        green.setActionCommand("changecolorGreen");

        changetext.addActionListener(this);

        label = new JLabel("Hello World!", SwingConstants.CENTER);
        label.setFont(new Font("Arial", Font.BOLD, 20));
        label.setForeground(new Color(0x009900));
        setLayout(new BorderLayout());
        add(label, BorderLayout.CENTER);
        add(changetext, BorderLayout.NORTH);
        add(red, BorderLayout.WEST);
        add(green, BorderLayout.EAST);
    }
    public void actionPerformed(ActionEvent e) {
        if ("change".equals(e.getActionCommand())) {
            label.setText("Hello Universe!");   
            changetext.setActionCommand("changeBack");
        }
        if ("changeBack".equals(e.getActionCommand())) {
            label.setText("Hello World!");
            changetext.setActionCommand("change");
        }
        if ("changecolorRed".equals(e.getActionCommand())) {
            label.setForeground(new Color(0xFF0000));
        }
        if ("changecolorGreen".equals(e.getActionCommand())) {
            label.setForeground(new Color(0x009900));
        }
    }
    private static void createWindow(){
        JFrame frame = new JFrame("Javagame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(500,500));

        JPanel panel = new JPanel(new BorderLayout());

        Javagame newContentPane = new Javagame();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);

        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        createWindow();
    }
}


推荐答案

这通常是通过一个简单的方法调用: red.addActionListener(someListener);

This is usually done via a simple method call: red.addActionListener(someListener);

另外:


  • code> setPreferredsize(...)方法调用,而是让组件设置自己的大小。最多可以覆盖 getPreferredSize()(如果需要),但尝试限制。

  • 避免让GUI代码监听器接口,因为这导致混乱和难以管理代码。更好地使用匿名内部侦听器或私有内部类或独立的侦听器类。

  • get rid of your setPreferredsize(...) method calls, and instead let components set their own size. At the most you can override getPreferredSize() if need be, but try to limit that.
  • Avoid having your GUI code implement your listener interfaces as that leads to confusing and difficult to manage code. Better to use anonymous inner listeners or private inner classes or stand alone listener classes.

例如:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class JavaGame2 extends JPanel {
   private static final int PREF_W = 600;
   private static final int PREF_H = 400;
   private static final Font LABEL_FONT = new Font("Arial", Font.BOLD, 20);
   private static final Color[] FOREGROUNDS = { new Color(0x009900),
         new Color(0x990000), new Color(0x000099), new Color(0x999900),
         new Color(0x990099), new Color(0x009999) };
   private static final String[] LABEL_TEXTS = { "Hello World!",
         "Goodbye World!", "Hola Todo el Mundo!", "Hasta la Vista Baby!",
         "Whatever!!" };

   private JButton changetextButton;
   private JButton changeColorButton;
   private JLabel label;
   private int labelTextIndex = 0;
   private int foregroundIndex = 0;

   public JavaGame2() {
      label = new JLabel(LABEL_TEXTS[labelTextIndex], SwingConstants.CENTER);
      label.setFont(LABEL_FONT);
      label.setForeground(FOREGROUNDS[foregroundIndex]);

      // example of anonymous inner ActionListener:
      changetextButton = new JButton("Change Text");
      changetextButton.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent evt) {
            labelTextIndex++;
            labelTextIndex %= LABEL_TEXTS.length;
            label.setText(LABEL_TEXTS[labelTextIndex]);
         }
      });

      // example of use of an anonymous AbstractAction:
      changeColorButton = new JButton(new AbstractAction("Change Color") {

         @Override
         public void actionPerformed(ActionEvent e) {
            foregroundIndex++;
            foregroundIndex %= FOREGROUNDS.length;
            label.setForeground(FOREGROUNDS[foregroundIndex]);
         }
      });

      setLayout(new BorderLayout());
      add(changetextButton, BorderLayout.NORTH);
      add(changeColorButton, BorderLayout.SOUTH);
      add(label, BorderLayout.CENTER);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

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

      JFrame frame = new JFrame("Java Game 2");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

这篇关于我可以使用getActionCommand来改变标签内容,但是我不能用它来改变颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆