Скопируйте текст из JTextField в JTextArea

1

Почему я не могу скопировать текст из JTextField в JTextArea? orders - это JTextArea а get - JTextField. Статус - JButton.

клиент класса:

  public client() extends superclass{
        super("CLIENT");
        setLayout(new FlowLayout());
        update = new JLabel("status");
        add(update,BorderLayout.SOUTH);
        order = new JPanel();
        add(order,BorderLayout.SOUTH);
        menu = new JList(kveb);
        menu.setVisibleRowCount(8);
        menu.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        add(new JScrollPane(menu));
        get = new JTextField("chaweret rac gsurt");
        add(get);
        status = new JButton("ORDER!");
        status.setFont(new Font("Serif",Font.BOLD,16));    
        add(status);
        guga k1 = new guga();
        menu.addListSelectionListener(k1);
        get.addActionListener(k1);
        status.addActionListener(k1);
        server tes = new server();
        tes.setSize(300,300);
        tes.setDefaultCloseOperation(EXIT_ON_CLOSE);
        tes.setVisible(true);
    }

сервер класса:

public class server extends superclass{
    public server() {
        super("SERVER");
        setLayout(new FlowLayout());
        // public JCheckBox ready;
         // public JCheckBox working;
         // public JCheckBox ordered;
          //public JCheckBox trans;
        //  public JTextField orders;
        ready = new JCheckBox("text");
        ready.setFont(new Font("Serif",Font.BOLD,16));
        add(ready);
         Font x = new Font("Serif",Font.BOLD,16);
         working = new JCheckBox("text here");
         working.setFont(x);
         add(working);
         migebulia = new JCheckBox("text heere");
         migebulia.setFont(x);
         add(migebulia);
         trans = new JCheckBox("mtext");
         trans.setFont(x);
         add(trans);
         orders = new JTextArea("text");
         orders.setFont(new Font("Serif",Font.BOLD,16));
         add(orders);
         guga k2 = new guga();
         ready.addActionListener(k2);
         working.addActionListener(k2);
         ordered.addActionListener(k2);
         trans.addActionListener(k2);
        // orders.addActionListener(k2);    
    }    
}

супер класс:

public class superclass extends  JFrame {
      //client
      public JList menu;
      public  JTextField get;
      public JPanel order;
      public JButton status;
      public String kveb[] = {"text","texti","text","text"};
      public JLabel update;
      //server
      public JCheckBox ready;
      public JCheckBox working;
      public JCheckBox ordered;
      public JCheckBox trans;
      public   JTextArea orders;

    public superclass(String string) {

    }

    class guga implements ActionListener, ListSelectionListener,DocumentListener{
        public void actionPerformed(ActionEvent event){
            if(event.getSource() == status){
                event.setSource(get);
                 orders.setText(get.getText());
            }
        }
    }
}
  • 0
    Что происходит, когда исполняется этот кусок кода? Вы вообще получаете текст в JTextArea ? Что возвращает get.getText() ?
  • 2
    MCVE
Показать ещё 1 комментарий
Теги:
text
swing
jtextfield
jtextarea

2 ответа

1
Лучший ответ

Если вы хотите скопировать текст только при ударе по status кнопки, вы можете сделать следующее:

status.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent pE) {
        orders.setText(get.getText());
    }
});

Если вы хотите скопировать из фрейма Server Frame to Client или наоборот, вам необходимо передать целевой компонент родительскому классу в конструкторе:

JTextArea destTextArea;
public superclass(String string, JTextArea pDestTextArea) {
    destTextArea = pDestTextArea;
}
....
public void actionPerformed(ActionEvent event){
    if ((event.getSource() == status) && (destTextArea != null)) {
        destTextArea.setText(get.getText());
    }
}

Затем создайте свой клиент и сервер:

super("CLIENT", null);
super("SERVER", orders);

или:

super("CLIENT", orders);
super("SERVER", null);
  • 0
    но я хочу, чтобы при нажатии статуса JButton скопировать его, я пробовал ActionListener, но он не работает!
  • 0
    Возможно, он не работает, потому что у меня есть два класса, но я использую наследование, поэтому мне нужно сделать JtextField в другом классе, а JTextArea в другом классе.
Показать ещё 9 комментариев
0

Я не знаю, какова структура вашего приложения, но попытайтесь объединить то, что я публикую здесь, с вашим текущим кодом с минимальными изменениями. Как только это сработает, вы можете начать движение вокруг.

Класс клиента:

public class Client {

    public JTextField get = new JTextField("chaweret rac gsurt");
    public JButton status = new JButton("ORDER!");

    Client() {

        status.addActionListener(new Superclass.MyListener());
    }
}

Класс сервера:

public class Server {

    public JTextArea orders = new JTextArea("text");
}

Класс суперкласса:

public class Superclass {

    static Client client = new Client();
    static Server server = new Server();

    public static class MyListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            if (e.getSource().equals(client.status))
                server.orders.setText(client.get.getText());
        }
    }
}

Примечание: имена классов должны начинаться с буквы верхнего регистра в соответствии с соглашениями Java.

  • 0
    это не работает, потому что статус JButton
  • 1
    Если вы пытаетесь скопировать текст при нажатии кнопки, используйте ActionListener .
Показать ещё 4 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню