到目前为止,我已经有了这段代码,在这里我希望创建的文本字段能够接受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
}
}
答案 0 :(得分:0)
变量名称不应以大写字母开头。有些是正确的。其他不是。保持一致。
请勿使用“标签”和“文本字段”。这些是AWT组件。在Swing应用程序中,您应该使用 if type(links) is not list:
links=[links]
和JLabel
。
您可能要考虑使用JTextField
,因为可以对其进行配置以确保仅输入0到255之间的数字。请阅读How to Use Spinners上Swing教程中的部分
按下“更改颜色”按钮时
然后,您需要向按钮添加一个ActionListener。阅读有关How to Use Buttons的Swing教程中的部分,以获取入门的实用示例。
然后在ActionListener中,从微调器中获取值
JSpinner