Как получить выбранный элемент из JMenu для изменения цвета текста в текстовой области? - PullRequest
0 голосов
/ 29 апреля 2018

Мне нужно написать текстовый редактор для моего класса, используя JTextArea, и одно из требований - иметь цветное меню, которое меняет цвет текста, когда он выбирается из меню. Я создал цветное меню с несколькими цветами и реализовал ActionListener, который вызывает textArea.setForeground (Color), но цвет текста никогда не меняется с черного. Вот два раздела, над которыми я работаю, но в конце я также предоставил код для всей программы.

Вот код для 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 ]

0 голосов
/ 02 мая 2018

Проблема в использовании метода JMenuItem.isSelected() в public void actionPerformed(ActionEvent e). JMenuItem.isSelected() работает для кнопки . Он присутствует здесь, потому что это метод из AbstractButton, но его значение всегда установлено на false.

Чтобы решить проблему в вашем случае, используйте ActionEvent.getActionCommand() 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;
  }
}
0 голосов
/ 29 апреля 2018

Я постараюсь помочь. Во-первых, нет ничего под названием ColorListener, который вы ссылаетесь на своего собственного КОНСТРУКТОРА! (Нет, вы не сейчас, когда я видел весь код, мой плохой) Вместо написания строки:

black.addActionListener(new ColorListener());

Вместо этого напишите это для вызова фактического ActionListener:

black.addActionListener(this);

Ключевое слово "this" в этом случае относится к методу actionPerformed. Но сделайте это со всеми JMenuItems (черный, розовый, зеленый и т. Д.).

Если это тебе не поможет. Предоставьте мне все файлы кода, чтобы я мог скопировать их и запустить вашу программу.

ОБНОВЛЕНИЕ:

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);

  }
}

Кажется, это работает, но я не могу понять, почему. Может быть, вы можете.

...