gpt4 book ai didi

java - jTextField 和 Jpanel 颜色输出

转载 作者:行者123 更新时间:2023-12-01 12:14:41 26 4
gpt4 key购买 nike

创建一个程序,您可以在文本字段中输入颜色名称,然后使用该颜色将面板背景颜色设置为文本字段中指定的颜色 我无法获取输出

import javax.swing.*;

import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingUtilities;

public class textfield implements ActionListener{

JTextField Input;
JPanel color;
JButton Button;

public JPanel createContentPane (){

// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);

// Creation of a Panel to contain the JLabels
Input = new JTextField ("color", 35);
Input.setBackground (Color.white);
Input.setLocation(50,50);
Input.setSize(100, 30);
Input.addActionListener (this);
totalGUI.add(Input);

color = new JPanel();
color.setBackground (Color.white);
color.setLocation(200, 50);
color.setSize(200, 100);
totalGUI.add(color);


totalGUI.setOpaque(true);
return totalGUI;
}

public void actionPerformed(ActionEvent e) {

String text = Input.getText();
{ if (text == "green")
color.setBackground(color.green);
}
}

private static void createAndShowGUI() {

JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Assignment");

textfield demo = new textfield();
frame.setContentPane(demo.createContentPane());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setVisible(true);
}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

最佳答案

有一些问题。

  1. 您应该使用 equals 方法而不是 == 来比较字符串的相等性。

  2. 将 color.green 更改为 Color.GREEN

    public void actionPerformed(ActionEvent e) {

    String text = Input.getText();
    if (text.equals("green"))
    {
    color.setBackground(Color.GREEN);
    }
    }

对于多种颜色,您可以使用if-else切换大小写

使用if-else:

   public void actionPerformed(ActionEvent e) {

String text = Input.getText();
if (text.equals("green"))
{
color.setBackground(Color.GREEN);
}
else if(text.equals("red"))
{
color.setBackground(Color.RED);
}
else if(text.equals("yellow"))
{
color.setBackground(Color.YELLOW);
}
else
{
color.setBackground(Color.BLUE);
}

}

使用开关盒:

public void actionPerformed(ActionEvent e) {

String text = Input.getText();

switch (text) {
case "green":
color.setBackground(Color.GREEN);
break;
case "red":
color.setBackground(Color.RED);
break;
case "yellow":
color.setBackground(Color.YELLOW);
break;
case "blue":
color.setBackground(Color.BLUE);
break;

}

}

关于java - jTextField 和 Jpanel 颜色输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27086707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com