对于我的作业,我必须创建一个基于框架的应用程序,该应用程序允许用户在三个文本字段中指定RGB值,并在按下按钮时以所选颜色显示我的姓名和注册号。我相信到目前为止,我所有的代码都是正确的,但是看起来零件颜色有问题。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ex1 extends JFrame {
JLabel label;
JTextField r, g, b;
public ex1() {
//panels to hold information
JPanel bottomPanel = new JPanel();
JPanel upperPanel = new JPanel();
//fields that will hold the colour values
r = new JTextField("Red", 10);
g = new JTextField("Green", 10);
b = new JTextField("Blue", 10);
//add to frame
bottomPanel.add(r);
bottomPanel.add(g);
bottomPanel.add(b);
add(bottomPanel, BorderLayout.SOUTH);
add(upperPanel, BorderLayout.CENTER);
label = new JLabel("CE203 Assignment 1, submitted by:");
label.setForeground(new Color(255, 0, 0));
JButton button = new JButton("Enter");
upperPanel.add(label);
bottomPanel.add(button);
button.addActionListener(new ButtonHandler(this));
}
public JLabel getLabel() {
return label;
}
class ButtonHandler implements ActionListener {
private ex1 assignment1;
public ButtonHandler(ex1 assignment1) {
this.assignment1 = assignment1;
}
@Override
public void actionPerformed(ActionEvent e) {
int r1 = Integer.parseInt(assignment1.r.getText());
int g1 = Integer.parseInt(assignment1.g.getText());
int b1 = Integer.parseInt(assignment1.b.getText());
assignment1.getLabel().setForground(new Color(r1, g1, b1));
}
}
public static void main(String[] args) {
JFrame frame = new ex1();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(ex1.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
如果有人可以告诉我出了什么问题以及如何解决它,将不胜感激。
当IDE报告编译错误时,请不要忽略它!
assignment1.getLabel().setForground(new Color(r1, g1, b1));
应该:
assignment1.getLabel().setForeground(new Color(r1, g1, b1));
代替:
frame.setSize(400, 400); // random guess at required size
有:
frame.pack(); // calculates the required size
在现实世界的编程中,当一个JColorChooser
程序具有优越性时,用户会私自给程序员提供3个文本字段。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句