该程序应在框架的中心绘制一个填充的正方形,但用户必须确定颜色。我不知道为什么它不起作用。
SquareComponent.java
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import java.awt.Color;
import javax.swing.JOptionPane;
public class SquareComponent extends JComponent{
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
String input = JOptionPane.showInputDialog("Enter a color");
switch(input.toLowerCase()) {
case "black": Square s = new Square(Color.BLACK);
s.draw(g2);
break;
case "blue": Square s1 = new Square(Color.BLUE);
s1.draw(g2);
break;
case "cyan": Square s2 = new Quadrato(Color.CYAN);
s2.draw(g2);
break;
case "gray": Square s3 = new Square(Color.GRAY);
s3.draw(g2);
break;
case "light gray": Square s4 = new Square(Color.LIGHT_GRAY);
s4.draw(g2);
break;
default: Square s5 = new Square(Color.PINK);
s5.draw(g2);
}
}
}
Square.java
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Color;
public class Square{
public Square(Color color) {
this.color = color;
}
public void draw(Graphics2D g2) {
Rectangle box = new Rectangle(20, 20, 130, 180);
g2.draw(box);
g2.setColor(color);
g2.fill(box);
}
private Color color;
}
SquareViewer.java
import javax.swing.JFrame;
public class SquareViewer{
public static void main(String[] args){
JFrame frame = new JFrame();
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("Square");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SquareComponent component = new SquareComponent();
frame.add(component);
frame.setVisible(true);
}
}
如果我运行SquareViewer,则会显示JOptionPane。例如,我写“黑色”。它显示一个黑色正方形,但背景中带有JOptionPane。为什么它不能正常工作?
答案 0 :(得分:0)
一种绘画方法仅用于绘画。您永远不应提示您在绘画方法中输入。创建组件时,应该在main()方法中显示JOptionPane
一种绘制方法应绘制组件的状态。例如,当您使用setText()方法时,JLabel会绘制文本。因此,根据您的情况,Sqaure
对象是SquareComponent
的属性,因此您需要一种添加Square to you
SquareComponent and then you save the Square as a property. Then the
paintComponent()method simply paints the
Square的方法`。
在执行自定义绘画之前,您的绘画方法应始终清除背景。您没有,这也许就是为什么您看到JOptionPane的原因,因为尚未清除该区域。在下面的示例中,我扩展了JPanel,因为它具有默认功能,可以在调用super.paintComponent()时清除背景。
您的SquareComponent
类可能类似于:
public class SquareComponent extends JPanel
{
private Square square;
public SquareComponent(Square square)
{
this.square = square;
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
square.draw(g);
}
}
然后在您的main()
方法中执行以下操作:
Square square = getSquareColor();
SquareComponent component = new SquareComponent(square);
frame.add(component);
getSquareColor()
方法类似于:
private static Square getSquareColor()
{
String input = JOptionPane.showInputDialog("Enter a color");
switch(input.toLowerCase()) {
case "black": return new Square(Color.BLACK);
case "blue": return new Square(Color.BLUE);
...
}
return = new Square(Color.PINK);
}
这仍然不是最佳设计。我希望您的SquareComponent能够绘制多个Square对象。检出Custom Painting Approaches的设计即可实现这一目的。