2013-11-09 2 views
1

Я создаю метод шифрования, который принимает входные данные от JTextArea, и я получаю сообщение об ошибке:Как создать публичную строку из JTextArea?

'Недопустимый модификатор для ввода параметров; разрешено только окончательное '

Я прошел через многие сайты документации и другие статьи, и я ничего не нашел. Вот мой почти полный код:

Package lake. RAMBIT7; 

import java.awt.EventQueue; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JMenu; 
import javax.swing.JMenuBar; 
import javax.swing.JMenuItem; 
import javax.swing.JOptionPane; 
import javax.swing.JScrollPane; 
import javax.swing.JTextArea; 

import net.miginfocom.swing.MigLayout; 

public class RAMBIT7 implements ActionListener { 

    private JFrame frame; 

    /** 
    * Launch the application. 
    */ 
    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        RAMBIT7 window = new RAMBIT7(); 
        window.frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    /** 
    * Create the application. 
    */ 
    public RAMBIT7() { 
     initialize(); 
    } 

    /** 
    * Initialize the contents of the frame. 
    */ 
    private void initialize() { 
     frame = new JFrame(); 
     frame.setSize(800, 600); //1024x768, 800x600 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setTitle("RAMBIT7 Encryption Software 1.0.0"); 
     frame.setResizable(false); 

     /** 
     * 'Encrypt' and 'Decrypt' buttons 
     */ 

     JButton encrypt = new JButton("Encrypt"); 
     encrypt.addActionListener(this); 
     JButton decrypt = new JButton("Decrypt"); 
     decrypt.addActionListener(this); 

     /** 
     * JMenuBar 
     */ 

     JMenuBar bar = new JMenuBar(); 
     JMenu file = new JMenu("File"); 
     JMenu help = new JMenu("Help"); 
     JMenuItem about = new JMenuItem("About"); 
     JMenuItem license = new JMenuItem("License"); 
     JMenuItem close = new JMenuItem("Exit"); 
     file.add(close); 
     help.add(about); 
     help.add(license); 
     bar.add(file); 
     bar.add(help); 
     about.addActionListener(this); 
     license.addActionListener(this); 
     close.addActionListener(this); 
     frame.setJMenuBar(bar); 

     /** 
     * Text and input related stuff 
     */ 
     frame.getContentPane().setLayout(new MigLayout("", "[69px][71px,grow][]", "[23px][35.00][200px][][grow][]")); 
     frame.getContentPane().add(encrypt, "cell 0 0,alignx left,aligny top"); 
     frame.getContentPane().add(decrypt, "cell 2 0,alignx right,aligny top"); 
     JLabel lblCopyTextIn = new JLabel("Copy Text in here.");//JLabel 
     frame.getContentPane().add(lblCopyTextIn, "cell 1 1"); 
     JScrollPane scrollPane = new JScrollPane(); 
     frame.getContentPane().add(scrollPane, "cell 0 2 3 1,grow"); 
     JTextArea textArea = new JTextArea();//JTextArea 
     scrollPane.setViewportView(textArea); 
     textArea.setLineWrap(true); 
     JLabel lblOutputTextIn = new JLabel("Output text in RAMBIT7 encryption");//JLabel 
     frame.getContentPane().add(lblOutputTextIn, "cell 1 3"); 
     JScrollPane scrollPane_1 = new JScrollPane(); 
     frame.getContentPane().add(scrollPane_1, "cell 0 4 3 1,grow"); 
     JTextArea textArea_1 = new JTextArea();//JTextArea_1 
     scrollPane_1.setViewportView(textArea_1); 
     textArea_1.setEditable(false); 
     textArea_1.setLineWrap(true); 
     JLabel lblRambitEncryptionMethod = new JLabel("RAMBIT7 Encryption Method"); //JLabel 
     frame.getContentPane().add(lblRambitEncryptionMethod, "cell 1 5"); 

     public String input_0 = textArea.getText();//Error here 


    } 



    @Override 
    public void actionPerformed(ActionEvent e) { 
     String a = e.getActionCommand(); 
     if(a.equalsIgnoreCase("encrypt")) { 
      System.out.println("Begin RAMBIT7 encryption."); 
      encryptRAMBIT7(input); 
     } else if(a.equalsIgnoreCase("decrypt")) { 
      System.out.println("Begin RAMBIT7 decryption."); 
      decryptRAMBIT7(input); 
     } else if(a.equalsIgnoreCase("about")) { 
      System.out.println("Opening Program Specs..."); 
      JOptionPane.showMessageDialog(frame, "RAMBIT7 v1.0.0"); 
      System.out.println("Program Specs Closed."); 
     } else if(a.equalsIgnoreCase("license")) { 
      System.out.println("Opening License..."); 
      JOptionPane.showMessageDialog(frame, "You may not sell this program or say that any part of the code is yours."); 
      System.out.println("License closed."); 
     } else if(a.equalsIgnoreCase("exit")) { 
      System.out.println("Why, oh WHY CRUEL WORLD does that person have to close me?! I'm\na living thing too! Or maybe I'm an emotionless pig! NOOOOOOOO!"); 
      System.exit(3); 
     } 

    } 

} 
+0

Объявление 'public String input_0' как член класса – Raghunandan

ответ

3

Вы должны переосмыслить вашу структуру немного:

  • Даже если вы могли бы получить строку из JTextArea по времени создания, он не будет помогите вам немного. Когда JTextArea изменяет свой отображаемый текст, эта строка не изменится, поскольку строки являются инвариантами.
  • Аналогичным образом поле String не помогло бы, если только оно не было динамически связано с JTextArea через DocumentListener или что-то подобное.
  • Вместо этого сделайте JTextArea частным полем и при необходимости извлеките его строку.
  • Если другим классам нужен текст, создайте общедоступный метод public String getTextAreaText() и верните текст, сохраненный JTextArea в этом методе.

public class RAMBIT7 implements ActionListener { 

    private JFrame frame; 
    private JTextArea textarea = new JTextArea(); 

    // .... 

    private void initialize() { 

     // ..... 

     // JTextArea textArea = new JTextArea();//JTextArea 
     scrollPane.setViewportView(textArea); 
     textArea.setLineWrap(true); 

и в других местах:

if(a.equalsIgnoreCase("encrypt")) { 
     System.out.println("Begin RAMBIT7 encryption."); 
     encryptRAMBIT7(textarea.getText()); 
+0

:) beat me +1 .. – Sage

+0

@ user185164: вы не объявляете JTextArea в ** классе **, как я делаю выше. Пожалуйста, внимательно посмотрите, где это объявляется, прямо под вашей переменной JFrame. Попробуй еще раз. –

1

Вы просто не можете использовать ключевое слово public внутри метода. Модификаторы видимости используются для определения того, к каким членам каждого объекта можно получить доступ извне, другими объектами или классами. Вещи, которые вы объявляете внутри метода, не являются членами класса, а скорее являются вещами, которые существуют только в этом методе, поэтому модификаторы видимости не имеют никакого смысла.

0
public String input_0 = textArea.getText(); 

Любая переменная, объявленная внутри функции, является локальной для этой функции. Внешний мир не знает об этой переменной, кроме самой функции. следовательно, модификаторы доступа public, private или protected не применимы к локальной переменной экземпляра, например input_0, которая является локальной для initialize(). Опять же, этот код находится внутри функции initialize(), которая отвечает за инициализацию компонента графического интерфейса пользователя, его создание и добавление в контейнер, пользовательский ввод еще не выполнен, поэтому чтение текстового содержимого textArea означает меньше.

Смежные вопросы