我在让特定对象出现在我的框架/面板中时遇到问题。在下面的代码中,我有#34; Drawing"类型的对象。例如浅色,红色,黄色和绿色。该程序应该创建一个红绿灯,但另一个绘图不会出现,我不知道为什么。 light
与其他内容是分开的,因此如果背景覆盖它就不会受到影响,但这不是问题。圈子/灯光不会画,我不会看到我失踪的东西或我做错了什么。
What the frame should look like
package lab8;
import oracle.jvm.hotspot.jfr.JFR;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
enum shape{
circle,square;
}
public class TrafficLight2 extends JFrame {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
TrafficLight2(){
frame.setPreferredSize(new Dimension(500, 500));
frame.setLayout(new FlowLayout());
panel.setLayout(new FlowLayout());
TrafficLight t = new TrafficLight();
t.setPreferredSize(new Dimension(500,500));
panel.setPreferredSize(new Dimension(500,500));
panel.add(t,BorderLayout.CENTER);
Drawing light = new Drawing();
light.colour=Color.RED;
light.s=shape.circle;
repaint();
panel.add(light);
frame.add(light);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
new TrafficLight2();
}
class ButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
ButtonListener(){
}
}
class Drawing extends JPanel{
int width=50;
int height=50;
shape s;
Color colour;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int verticalCenter = getParent().getHeight()/2;
int horizontalCenter = getParent().getWidth()/2;
int topLeftSquareCornerY = verticalCenter - (height/2);
int topLeftSquareCornerX = horizontalCenter - (width/2);
g.setColor(colour);
if (s==shape.square) {
g.fillRect(topLeftSquareCornerX, topLeftSquareCornerY, width, height);
}
else{
g.fillOval(topLeftSquareCornerX,topLeftSquareCornerY,width,height);
}
}
}
class TrafficLight extends Drawing{
Drawing red = new Drawing();
Drawing yellow = new Drawing();
Drawing green = new Drawing();
Drawing background = new Drawing();
TrafficLight(){
this.red.s=shape.circle;
this.red.colour=Color.RED;
this.yellow.s=shape.circle;
this.yellow.colour=Color.YELLOW;
this.green.s=shape.circle;
this.green.colour=Color.GREEN;
this.background.s=shape.square;
this.background.colour=Color.BLACK;
this.background.width=100;
this.background.height=300;
this.s=shape.square;
this.colour=Color.BLACK;
this.width=100;
this.height=300;
background.add(red,BorderLayout.NORTH);
background.add(yellow,BorderLayout.CENTER);
background.add(green,BorderLayout.SOUTH);
this.add(background)
repaint();
}
}
}
答案 0 :(得分:0)
您忘了向TrafficLight添加背景。
TrafficLight(){
.... other stuff
this.add(background);
}
另外,我发现TrafficLight2扩展JFrame很奇怪,但实际上并未使用......