Create一個程序,你可以輸入顏色名稱到一個文本框,然後使用該顏色設置在文本字段中指定的顏色面板背景顏色 有問題即時得到輸出的JTextField和JPanel的彩色輸出
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();
}
});
}
}
我想要多種顏色,但沒有工作。 – 2014-11-23 08:50:27
我做了所需的更改,它適用於多種顏色。 – 2014-11-23 12:41:00
非常感謝 – 2014-11-23 13:26:58