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

Пока у меня есть этот код, и я хотел бы, чтобы созданные текстовые поля могли принимать входные данные для значений RGB, а затем, когда нажата кнопка «Изменить цвет», в кадре появится сообщение в цвете которые были указаны в текстовых полях, например если значения текстовых полей были красные: 255, синие: 0, зеленые: 0, этот цвет был бы цветом текста.

Я довольно новичок в Java, поэтому любая помощь в том, как я мог бы начать с этим, была бы оценена.

import javax.swing.*;
import java.awt.*;


public class Main {

public static void main(String[] args) {



    FilledFrame frame = new FilledFrame(); // Create new JFrame
    frame.setVisible( true ); // Set it to visible
    frame.setSize(500, 500); // Set size of JFrame window
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); // Set default close operation
    frame.setTitle("Change Colour"); // Set title of the JFrame window


}
}

class FilledFrame extends JFrame {

public FilledFrame()
{
    JButton mainButton = new JButton("Change Color"); // Create new button
    JPanel Panel = new JPanel(); // Create JPanel for the button

    Panel.add(mainButton); // Add button to the JFrame
    add(Panel, BorderLayout.SOUTH); // Set layout of the button to bottom of the window

    JLabel label = new JLabel("Welcome"); // Create the welcome message
    JPanel Panel1 = new JPanel(); // Create JPanel for the label

    Panel1.add(label); // Add label to the frame
    add(Panel1, BorderLayout.CENTER); // Set layout of the label to centre
    label.setForeground(Color.BLUE); // Set color of the label to blue

    Label red, green, blue;
    TextField redT, greenT, blueT;

    red = new Label("Red"); // Create label Red
    green = new Label("Green"); // Create Label Green
    blue = new Label("Blue"); // Create Label Blue

    redT = new TextField(5); // Create text field for input for red value
    greenT = new TextField(5); // Create text field for input green value
    blueT = new TextField(5); // Create text field for input blue value

    // Add the labels and text fields to the frame window

    Panel.add(red);
    Panel.add(redT);
    Panel.add(blue);
    Panel.add(blueT);
    Panel.add(green);
    Panel.add(greenT);

    add(Panel, BorderLayout.SOUTH); // Set position of the labels and text fields at bottom of the window
}

}

1 Ответ

0 голосов
/ 29 октября 2018
  1. Имена переменных НЕ должны начинаться с символа верхнего регистра. Некоторые из них верны. Другие нет. Будьте последовательны.

  2. Не используйте "Label" и "TextField". Это компоненты AWT. В приложении Swing вы должны использовать JLabel и JTextField.

  3. Вы можете рассмотреть возможность использования JSpinner, так как его можно настроить, чтобы убедиться, что вы вводите цифры только в диапазоне от 0 до 255. Прочитайте раздел из учебника по Swing на Как использовать счетчики

при нажатии кнопки «Изменить цвет»

Затем вам нужно добавить ActionListener к кнопке. Прочитайте раздел учебника по Swing на Как использовать кнопки , чтобы получить рабочий пример, чтобы начать работу.

Затем в ActionListener вы получаете значения из счетчика

int red = (Integer)redSpinner.getValue();
int green = (Integer)greenSpinner.getValue();
int blue = (Integer)blueSpinner.getValue();
Color color = new Color(red, green, blue);
label.setForeground( color );
...