Перемещение текста влево и вправо в графическом интерфейсе Java - PullRequest
0 голосов
/ 29 апреля 2018

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

Как мне это исправить?

import javafx.application.Application;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import static java.awt.FlowLayout.LEFT;
import static javax.swing.border.TitledBorder.LEFT;
import static javax.swing.JSplitPane.LEFT;
import static javax.swing.SwingConstants.LEFT;
import static java.awt.Event.LEFT;
import static java.awt.Label.LEFT;
import static javafx.geometry.HPos.LEFT;
import static javafx.geometry.HorizontalDirection.LEFT;
import static javafx.geometry.Side.LEFT;
import static javafx.scene.control.ButtonBar.ButtonData.LEFT;
import static javafx.scene.control.ContentDisplay.LEFT;
import static javafx.scene.input.KeyCode.LEFT;
import static javafx.scene.text.TextAlignment.LEFT;
import static com.sun.javafx.scene.traversal.Direction.LEFT;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;     
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;

public class Unit08_Prog1 extends JFrame implements ActionListener {
    //add Radio Button (colors)
    ButtonGroup colors = new ButtonGroup();
    JRadioButton red = new JRadioButton("Red");
    JRadioButton yellow = new JRadioButton("Yellow");
        JRadioButton white = new JRadioButton("White");
    JRadioButton orange = new JRadioButton("Orange");
    JRadioButton green = new JRadioButton("Green");
    //add text area
    JTextArea textArea = new JTextArea("Welcome to Java" , 5 , 30);
    //add buttons
    JButton  btLeft = new JButton("Left");
    JButton btRight = new JButton("Right");
    KeyListener keyListener;

    /**
     * @Description: populate frame with 3 panels
     * 
     *               1st changes colors 2nd edits text 3rd contains two buttons:
     *               Clear and Quit which have Mnemonics of "C" and "Q"
     */
    public Unit08_Prog1() {
        setLayout(new BorderLayout());
        //populate ButtonGroup
        colors.add(red);
        colors.add(yellow);
        colors.add(white);
        colors.add(orange);
        colors.add(green);
        // create panel 1 (panel changes text area's color)
        JPanel colorPanel = new JPanel();
        colorPanel.setLayout(new FlowLayout());
        colorPanel.setBorder(BorderFactory.createTitledBorder("Select Message Background"));
        colorPanel.add(red);
        colorPanel.add(yellow);
        colorPanel.add(white);
        colorPanel.add(orange);
        colorPanel.add(green);

        //Create panel 2 (add text area to frame)
        JPanel textPanel = new JPanel();
        textPanel.setLayout(new BorderLayout());
        textPanel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
        JScrollPane scroll = new JScrollPane(textArea);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        textPanel.add(scroll, BorderLayout.CENTER);

        //create panel 3 (add buttons to frame)
        JPanel btnPanel = new JPanel();
        btnPanel.add(btLeft);
        btnPanel.add(btRight);
        //add panels
        add(colorPanel, BorderLayout.NORTH);
        add(textPanel, BorderLayout.CENTER);
        add(btnPanel, BorderLayout.SOUTH);
        //add listeners
        red.addActionListener(this);
        yellow.addActionListener(this);
        orange.addActionListener(this);
        white.addActionListener(this);
        green.addActionListener(this);

        btLeft.addActionListener(this);
        btRight.addActionListener(this);
        btLeft.setMnemonic('c');
        btRight.setMnemonic('q');
//      addKeyListener((KeyListener) this);



    }
    /** Handle the key typed event from the text field. */
//    public void keyTyped(KeyEvent e) {
//      int key = e.getKeyCode();
//      if (key == KeyEvent.VK_C){
//          textArea.setText("Welcome to Java");
//      }else if(key == KeyEvent.VK_Q){
//          System.exit(0);
//      }
//    }
//     
//    /** Handle the key pressed event from the text field. */
//    public void keyPressed(KeyEvent e) {
//      int key = e.getKeyCode();
//      if (key == KeyEvent.VK_C){
//          textArea.setText("Welcome to Java");
//      }else if(key == KeyEvent.VK_Q){
//          System.exit(0);
//      }
//    }
//     
//    /** Handle the key released event from the text field. */

    //    public void keyReleased(KeyEvent e) {
    //      int key = e.getKeyCode();

//      
    public static void main(String[] args) {
        // create frame
        Unit08_Prog1 frame = new Unit08_Prog1();
        frame.pack();
        frame.setMinimumSize(new Dimension(400,200));
        frame.setTitle("Unit08_Prog1");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        if(arg0.getSource() == red){
            textArea.setBackground(Color.RED);
        }else if(arg0.getSource() == yellow){
            textArea.setBackground(Color.YELLOW);
        }else if(arg0.getSource() == orange){
            textArea.setBackground(Color.LIGHT_GRAY);
        }else if(arg0.getSource() == white){
            textArea.setBackground(Color.WHITE);
        }else if(arg0.getSource() == green){
            textArea.setBackground(Color.GREEN);

    }

}

1 Ответ

0 голосов
/ 29 апреля 2018

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

Во-вторых, я думаю, вам стоит подумать о своем коде. Реализация ActionListener и обработка различных типов действий в одном месте, на мой взгляд, не очень хорошая идея.

Итак, я обнаружил, что выравнивание текста с помощью JTextArea довольно проблематично, потому что, хотя оно работает, оно начинает работать при изменении текста внутри области, что странно.

Можете ли вы использовать JTextField вместо этого? Если вы можете, вот решение для вашего конкретного случая:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

public class Unit08_Prog1 extends JFrame implements ActionListener {
    //add Radio Button (colors)
    ButtonGroup colors = new ButtonGroup();
    JRadioButton red = new JRadioButton("Red");
    JRadioButton yellow = new JRadioButton("Yellow");
    JRadioButton white = new JRadioButton("White");
    JRadioButton orange = new JRadioButton("Orange");
    JRadioButton green = new JRadioButton("Green");
    //add text area
    JTextField textArea = new JTextField("Welcome to Java");
    JScrollPane scroll;
    //add buttons
    JButton btLeft = new JButton("Left");
    JButton btRight = new JButton("Right");
    KeyListener keyListener;

    /**
     * @Description: populate frame with 3 panels
     * <p>
     * 1st changes colors 2nd edits text 3rd contains two buttons:
     * Clear and Quit which have Mnemonics of "C" and "Q"
     */
    public Test() {
        setLayout(new BorderLayout());
        //populate ButtonGroup
        colors.add(red);
        colors.add(yellow);
        colors.add(white);
        colors.add(orange);
        colors.add(green);
        // create panel 1 (panel changes text area's color)
        JPanel colorPanel = new JPanel();
        colorPanel.setLayout(new FlowLayout());
        colorPanel.setBorder(BorderFactory.createTitledBorder("Select Message Background"));
        colorPanel.add(red);
        colorPanel.add(yellow);
        colorPanel.add(white);
        colorPanel.add(orange);
        colorPanel.add(green);

        //Create panel 2 (add text area to frame)
        JPanel textPanel = new JPanel();
        textPanel.setLayout(new BorderLayout());
        textPanel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
        scroll = new JScrollPane(textArea);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        textPanel.add(scroll, BorderLayout.CENTER);

        //create panel 3 (add buttons to frame)
        JPanel btnPanel = new JPanel();
        btnPanel.add(btLeft);
        btnPanel.add(btRight);
        //add panels
        add(colorPanel, BorderLayout.NORTH);
        add(textPanel, BorderLayout.CENTER);
        add(btnPanel, BorderLayout.SOUTH);
        //add listeners
        red.addActionListener(this);
        yellow.addActionListener(this);
        orange.addActionListener(this);
        white.addActionListener(this);
        green.addActionListener(this);

        btLeft.addActionListener(this);
        btRight.addActionListener(this);
        btLeft.setMnemonic('c');
        btRight.setMnemonic('q');
//      addKeyListener((KeyListener) this);


    }

    /**
     * Handle the key typed event from the text field.
     */
//    public void keyTyped(KeyEvent e) {
//      int key = e.getKeyCode();
//      if (key == KeyEvent.VK_C){
//          textArea.setText("Welcome to Java");
//      }else if(key == KeyEvent.VK_Q){
//          System.exit(0);
//      }
//    }
//     
//    /** Handle the key pressed event from the text field. */
//    public void keyPressed(KeyEvent e) {
//      int key = e.getKeyCode();
//      if (key == KeyEvent.VK_C){
//          textArea.setText("Welcome to Java");
//      }else if(key == KeyEvent.VK_Q){
//          System.exit(0);
//      }
//    }
//     
//    /** Handle the key released event from the text field. */

    //    public void keyReleased(KeyEvent e) {
    //      int key = e.getKeyCode();

//      
    @Override
    public void actionPerformed(ActionEvent arg0) {
        if (arg0.getSource() == red) {
            textArea.setBackground(Color.RED);
        } else if (arg0.getSource() == yellow) {
            textArea.setBackground(Color.YELLOW);
        } else if (arg0.getSource() == orange) {
            textArea.setBackground(Color.LIGHT_GRAY);
        } else if (arg0.getSource() == white) {
            textArea.setBackground(Color.WHITE);
        } else if (arg0.getSource() == green) {
            textArea.setBackground(Color.GREEN);
        } else if ("Left".equals(arg0.getActionCommand())) {
            textArea.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        } else if ("Right".equals(arg0.getActionCommand())) {
            textArea.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        }
    }
}

Еще раз, я не внес никаких изменений в ваш код, но я думаю, что вы должны.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...