我正在用java编写一个程序,它根据鼠标坐标在屏幕上绘制一个矩形。但是,我无法获得此矩形的正确颜色。目标是在用户单击屏幕并选择颜色后绘制具有正确颜色的矩形。我尝试过案例场景,但无法正常使用。不工作的部分被评论。
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.geom.*;
import java.awt.event.*;
public class test extends JFrame implements ActionListener, MouseListener, KeyListener {
Shape box = new Rectangle2D.Float(10, 10, 10, 10);
public test () {
setSize(250,150);
addMouseListener(this);
addKeyListener(this);
Color bgColor = new Color(125,125,125);
setBackground(bgColor);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
test frame = new test();
frame.setVisible(true);
}
});
}
public void actionPerformed(ActionEvent ae) {
}
public void drawRectangle(int x, int y) {
Graphics g = this.getGraphics();
// KeyEvent e = this.getKeyChar();
// switch (test.keyTyped()) {
// case b:
g.drawRect(x, y, x, y);
g.setColor(Color.BLUE);
g.fillRect(x, y, 2, 2);
// case r:
// g.drawRect(x, y, x, y);
// g.setColor(Color.RED);
// g.fillRect(x, y, 2, 2);
// case y:
// g.drawRect(x, y, x, y);
// g.setColor(Color.Yellow);
// g.fillRect(x, y, 2, 2);
// case g:
// g.drawRect(x, y, x, y);
// g.setColor(Color.GREEN);
// g.fillRect(x, y, 2, 2);
//}
}
int x, y;
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
c = Character.toLowerCase(c);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.white);
g.drawString("Click anywhere to draw a rectangle", 50, 250);
g.drawString("Choose color by pressing the corresponding key on your keyboard: ", 50, 270);
g.setColor(Color.blue);
g.drawString("B: Blue ", 50, 285);
g.setColor(Color.red);
g.drawString("R: Red ", 95, 285);
g.setColor(Color.yellow);
g.drawString("Y: Yellow ", 140, 285);
g.setColor(Color.green);
g.drawString("G: Green ", 195, 285);
drawRectangle(x, y);
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:4)
您正在对图形颜色状态的颜色进行硬编码:
g.setColor(Color.BLUE);
因此,无论用户选择什么,它都会保持蓝色毫无疑问。
建议:
rectangleColor
repaint()
。getGraphics()
来获取Graphics对象 - 而是使用JVM为您提供的Graphics对象在paintComponent方法中进行绘制。super.paintComponent(g)
。这将允许JPanel进行管家绘画。答案 1 :(得分:4)
您可以这样做:
Expression