有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从JMenu中获取所选项以更改文本区域的文本颜色?

我必须使用JTextArea为我的类编写一个文本编辑器,其中一个要求是拥有一个颜色菜单,当从菜单中选择一个时,该菜单可以更改文本的颜色。我已经用几种颜色设置了一个颜色菜单,并实现了一个调用textArea的ActionListener。设置前景(颜色),但文本颜色从不从黑色更改。下面是我正在处理的两个部分,但最后我还提供了整个程序的代码

以下是JMenu的代码:

private void buildColorMenu()
{
  // Create the radio button menu items to change
  // the color of the text. Add an action listener
  // to each one.
  black = new JMenuItem("Black");
  black.addActionListener(new ColorListener());

  red = new JMenuItem("Red");
  red.addActionListener(new ColorListener());

  green = new JMenuItem("Green");
  green.addActionListener(new ColorListener());

  blue = new JMenuItem("Blue");
  blue.addActionListener(new ColorListener());

  orange = new JMenuItem("Orange");
  orange.addActionListener(new ColorListener());

  pink = new JMenuItem("Pink");
  pink.addActionListener(new ColorListener());

  yellow = new JMenuItem("Yellow");
  yellow.addActionListener(new ColorListener());

  colorMenu = new JMenu("Color");
  colorMenu.setMnemonic(KeyEvent.VK_O);

  colorMenu.add(black);
  colorMenu.add(red);
  colorMenu.add(green);
  colorMenu.add(blue);
  colorMenu.add(orange);
  colorMenu.add(pink);
  colorMenu.add(yellow);

  // Add the menu items to the Text menu.
}

下面是ActionListener代码:

private class ColorListener implements ActionListener
{
  public void actionPerformed(ActionEvent e)
  {
      if (black.isSelected())
          textArea.setForeground(Color.BLACK);
      else if (red.isSelected())
          textArea.setForeground(Color.RED);
      else if (green.isSelected())
          textArea.setForeground(Color.GREEN);
      else if (blue.isSelected())
          textArea.setForeground(Color.BLUE);
      else if (orange.isSelected())
          textArea.setForeground(Color.ORANGE);
      else if (pink.isSelected())
          textArea.setForeground(Color.PINK);
      else if (yellow.isSelected())
          textArea.setForeground(Color.YELLOW);

  }
}

有人能帮忙吗

以下是整个程序的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

/**
The MenuWindow class demonstrates a menu system.
*/

public class TextEditor extends JFrame
{

// The following will reference menu components.
private JTextArea textArea;
private JMenuBar menuBar;    // The menu bar
private JMenu fileMenu;      // The File menu
private JMenu colorMenu;      // The Color menu
private JMenu fontMenu;
private JMenuItem newItem;
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;
private JMenuItem exitItem;  // To exit
private JMenuItem black, red, green, blue, orange, pink, yellow;
private JRadioButtonMenuItem Monospaced; // Makes text black
private JRadioButtonMenuItem Serif;   // Makes text Serif
private JRadioButtonMenuItem SansSerif;  // Makes text SansSerif
private JCheckBoxMenuItem Italic;  // Makes text Italic
private JCheckBoxMenuItem Bold;

/**
  Constructor
*/

public TextEditor()
{
  // Set the title.
  setTitle("Text Editor");

  // Specify an action for the close button.
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  textArea = new JTextArea(20, 50);

  JScrollPane scrollPane = new JScrollPane(textArea);

  textArea.setEditable(true);


  add(scrollPane);

  // Build the menu bar.
  buildMenuBar();

  // Pack and display the window.
  pack();
  setVisible(true);
}

/**
  The buildMenuBar method builds the menu bar.
*/

private void buildMenuBar()
{
  // Create the menu bar.
  menuBar = new JMenuBar();

  // Create the file and text menus.
  buildFileMenu();
  buildColorMenu();
  buildFontMenu();

  // Add the file and text menus to the menu bar.
  menuBar.add(fileMenu);
  menuBar.add(fontMenu);
  menuBar.add(colorMenu);

  // Set the window's menu bar.
  setJMenuBar(menuBar);
}

/**
  The buildFileMenu method builds the File menu
  and returns a reference to its JMenu object.
*/

private void buildFileMenu()
{
  // Create an Exit menu item.
  newItem = new JMenuItem("New");
  newItem.setMnemonic(KeyEvent.VK_N);
  newItem.addActionListener(new NewFileListener());

  openItem = new JMenuItem("Open");
  openItem.setMnemonic(KeyEvent.VK_O);
  openItem.addActionListener(new OpenListener());

  saveItem = new JMenuItem("Save");
  saveItem.setMnemonic(KeyEvent.VK_S);
  saveItem.addActionListener(new SaveListener());

  saveAsItem = new JMenuItem("Save As");
  saveAsItem.setMnemonic(KeyEvent.VK_A);
  saveAsItem.addActionListener(new SaveAsListener());

  exitItem = new JMenuItem("Exit");
  exitItem.setMnemonic(KeyEvent.VK_X);
  exitItem.addActionListener(new ExitListener());

  // Create a JMenu object for the File menu.
  fileMenu = new JMenu("File");
  fileMenu.setMnemonic(KeyEvent.VK_F);

  // Add the Exit menu item to the File menu.
  fileMenu.add(newItem);
  fileMenu.add(openItem);
  fileMenu.addSeparator();
  fileMenu.add(saveItem);
  fileMenu.add(saveAsItem);
  fileMenu.addSeparator();
  fileMenu.add(exitItem);
}

/**
  The buildcolorMenu method builds the Text menu
  and returns a reference to its JMenu object.
*/

private void buildColorMenu()
{
  // Create the radio button menu items to change
  // the color of the text. Add an action listener
  // to each one.
  black = new JMenuItem("Black");
  black.addActionListener(new ColorListener());

  red = new JMenuItem("Red");
  red.addActionListener(new ColorListener());

  green = new JMenuItem("Green");
  green.addActionListener(new ColorListener());

  blue = new JMenuItem("Blue");
  blue.addActionListener(new ColorListener());

  orange = new JMenuItem("Orange");
  orange.addActionListener(new ColorListener());

  pink = new JMenuItem("Pink");
  pink.addActionListener(new ColorListener());

  yellow = new JMenuItem("Yellow");
  yellow.addActionListener(new ColorListener());

  // Create a button group for the radio button items.


  // Create a check box menu item to make the text
  // visible or invisible.

  // Create a JMenu object for the Text menu.
  colorMenu = new JMenu("Color");
  colorMenu.setMnemonic(KeyEvent.VK_O);

  colorMenu.add(black);
  colorMenu.add(red);
  colorMenu.add(green);
  colorMenu.add(blue);
  colorMenu.add(orange);
  colorMenu.add(pink);
  colorMenu.add(yellow);

  // Add the menu items to the Text menu.

}
private void buildFontMenu()
{
  Monospaced = new JRadioButtonMenuItem("Monospaced", true);
  Monospaced.addActionListener(new FontListener());

  Serif = new JRadioButtonMenuItem("Serif");
  Serif.addActionListener(new FontListener());

  SansSerif = new JRadioButtonMenuItem("SansSerif");
  SansSerif.addActionListener(new FontListener());

  Italic = new JCheckBoxMenuItem("Italic");
  Italic.addActionListener(new FontListener());

  Bold = new JCheckBoxMenuItem("Bold");
  Bold.addActionListener(new FontListener());

  ButtonGroup group = new ButtonGroup();
  group.add(Monospaced);
  group.add(Serif);
  group.add(SansSerif);

  fontMenu = new JMenu("Font");
  fontMenu.setMnemonic(KeyEvent.VK_N);

  fontMenu.add(Monospaced);
  fontMenu.add(Serif);
  fontMenu.add(SansSerif);
  fontMenu.addSeparator();
  fontMenu.add(Italic);
  fontMenu.add(Bold);
}

/**
  Private inner class that handles the event that
  is generated when the user selects Exit from
  the File menu.
*/

private class NewFileListener implements ActionListener
{
  public void actionPerformed(ActionEvent e)
  {
     textArea.setText(null);
  }
}

private class OpenListener implements ActionListener
{
  public void actionPerformed(ActionEvent e)
  {
      JFileChooser fileChooser = new JFileChooser();
      int status = fileChooser.showOpenDialog(textArea);
      String str="";
      if (status == JFileChooser.APPROVE_OPTION)
      {
        File selectedFile = fileChooser.getSelectedFile();
        Scanner inputFile;
        try 
        {
            inputFile = new Scanner(selectedFile);
            while (inputFile.hasNext())
            {
                str = str+inputFile.nextLine();                 
            }
            textArea.setText(str);
            inputFile.close();
        } 
        catch (FileNotFoundException e1) 
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

      }

  }
}

private class SaveAsListener implements ActionListener
{
  public void actionPerformed(ActionEvent e)
  {
      JFileChooser fileChooser = new JFileChooser();
      int status = fileChooser.showSaveDialog(textArea);
      if (status == JFileChooser.APPROVE_OPTION)
      {
          try 
          {
            File fileSave = fileChooser.getSelectedFile();
            PrintWriter outputfile = new PrintWriter(fileSave + ".txt");
            outputfile.println(textArea.getText());
            outputfile.close();
          } 
          catch (FileNotFoundException e1) 
          {
            // TODO Auto-generated catch block
            e1.printStackTrace();
          }
      }

  }
}

private class SaveListener implements ActionListener
{
  public void actionPerformed(ActionEvent e)
  {
      {
            PrintWriter outputfile = null;
            try 
            {
                outputfile = new PrintWriter("Names.txt");
            } 
            catch (FileNotFoundException e1) 
            {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            outputfile.println(textArea.getText());
            outputfile.close();

      }

  }


}

private class ColorListener implements ActionListener
{
  public void actionPerformed(ActionEvent e)
  {
      if (black.isSelected())
          textArea.setForeground(Color.BLACK);
      else if (red.isSelected())
          textArea.setForeground(Color.RED);
      else if (green.isSelected())
          textArea.setForeground(Color.GREEN);
      else if (blue.isSelected())
          textArea.setForeground(Color.BLUE);
      else if (orange.isSelected())
          textArea.setForeground(Color.ORANGE);
      else if (pink.isSelected())
          textArea.setForeground(Color.PINK);
      else if (yellow.isSelected())
          textArea.setForeground(Color.YELLOW);

  }
}

private class ExitListener implements ActionListener
{
   public void actionPerformed(ActionEvent e)
   {
      System.exit(0);
   }
}

/**
  Private inner class that handles the event that
  is generated when the user selects a color from
  the Text menu.
*/

private class FontListener implements ActionListener
{
   public void actionPerformed(ActionEvent e)
   {
      {
      if (Monospaced.isSelected())
          textArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
      else if (Serif.isSelected())
          textArea.setFont(new Font(Font.SERIF, Font.PLAIN, 14));
      else if (SansSerif.isSelected())
          textArea.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 14));
      }
      if (Italic.isSelected() && Bold.isSelected())
          textArea.setFont(new Font(textArea.getText(), Font.BOLD + 
          Font.ITALIC, 14));
      else if (Italic.isSelected())
          textArea.setFont(new Font(textArea.getText(), Font.ITALIC, 14));
      else if (Bold.isSelected())
          textArea.setFont(new Font(textArea.getText(), Font.BOLD, 14));
   }
}

/**
  Private inner class that handles the event that
  is generated when the user selects Visible from
  the Text menu.
*/


/**
  The main method creates an instance of the
  MenuWindow class, which causes it to display
  its window.
*/

public static void main(String[] args)
{
  new TextEditor();
}
}

共 (2) 个答案

  1. # 1 楼答案

    我会尽力帮忙的。首先,这里没有所谓的ColorListener,你指的是你自己的构造函数!(不,当我看到整个代码时,你现在不是了,我的错)而不是写这行:

    black.addActionListener(new ColorListener());
    

    而是编写以下代码来调用实际的ActionListener:

    black.addActionListener(this);
    

    本例中的关键字“this”是指actionPerformed方法。 但是对所有的项目(黑色、粉色、绿色等)都这样做

    如果这对你没有帮助。向我提供所有代码文件,以便我可以复制它们并运行您的程序

    更新:

    private class ColorListener implements ActionListener
    {
      public void actionPerformed(ActionEvent e)
      {
          if (e.getSource() == black)
              textArea.setForeground(Color.BLACK);
          else if (e.getSource() == red)
              textArea.setForeground(Color.RED);
          else if (e.getSource() == green)
              textArea.setForeground(Color.GREEN);
          else if (e.getSource() == blue)
              textArea.setForeground(Color.BLUE);
          else if (e.getSource() == orange)
              textArea.setForeground(Color.ORANGE);
          else if (e.getSource() == pink)
              textArea.setForeground(Color.PINK);
          else if (e.getSource() == yellow)
              textArea.setForeground(Color.YELLOW);
    
      }
    }
    

    这似乎有效,但我不明白为什么。 也许你可以

  2. # 2 楼答案

    问题在于在public void actionPerformed(ActionEvent e)中使用JMenuItem.isSelected()方法JMenuItem.isSelected()适用于切换按钮。它出现在这里是因为它是来自^{}的方法,但其值始终设置为false

    要解决您案例中的问题,请使用^{}intead

    更改public void actionPerformed(ActionEvent e)的定义如下:

    public void actionPerformed(ActionEvent e)
    {
      switch(e.getActionCommand())
      {
      case "Black": textArea.setForeground(Color.BLACK); break;
      case "Red": textArea.setForeground(Color.RED); break;
      case "Green": textArea.setForeground(Color.GREEN); break;
      case "Blue": textArea.setForeground(Color.BLUE); break;
      case "Orange": textArea.setForeground(Color.ORANGE); break;
      case "Pink": textArea.setForeground(Color.PINK); break;
      case "Yellow": textArea.setForeground(Color.YELLOW); break;
      }
    }