我正在尝试在BlueJ中创建一个Java,它将通过点击按钮来改变红绿灯,例如,绿色变成绿色,黄色变成黄色,等等……
我当前的图像将灯光的位置放在左上角。我想居中的灯光和按钮,因为我也试图在图像周围添加一个厚厚的绿色边界以及。然而,每当我试图移动图像时,它就会水平翻转,或者如果我添加一个绿色的边界,它就会变成灯光旁边的一个框。我还试图将按钮移动到红绿灯的上方,而不是红绿灯的下方。
我可以在以下方面得到一些帮助:添加绿色边框,在边框内将灯光居中,并将按钮移动到灯光顶部(也在边框内居中)
任何帮助都将不胜感激。提前谢谢你!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class TrafficLight extends JFrame implements ActionListener {
JButton b1, b2, b3;
Signal green = new Signal(Color.green);
Signal yellow = new Signal(Color.yellow);
Signal red = new Signal(Color.red);
public TrafficLight(){
super("Traffic Light");
getContentPane().setLayout(new GridLayout(2, 1));
b1 = new JButton("Red");
b2 = new JButton("Yellow");
b3 = new JButton("Green");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
green.turnOn(false);
yellow.turnOn(false);
red.turnOn(true);
JPanel p1 = new JPanel(new GridLayout(3,1));
p1.add(red);
p1.add(yellow);
p1.add(green);
JPanel p2 = new JPanel(new FlowLayout());
p2.add(b1);
p2.add(b2);
p2.add(b3);
getContentPane().add(p1);
getContentPane().add(p2);
pack();
}
public static void main(String[] args){
TrafficLight tl = new TrafficLight();
tl.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == b1){
green.turnOn(false);
yellow.turnOn(false);
red.turnOn(true);
} else if (e.getSource() == b2){
yellow.turnOn(true);
green.turnOn(false);
red.turnOn(false);
} else if (e.getSource() == b3){
red.turnOn(false);
yellow.turnOn(false);
green.turnOn(true);
}
}
}
class Signal extends JPanel{
Color on;
int radius = 40;
int border = 10;
boolean change;
Signal(Color color){
on = color;
change = true;
}
public void turnOn(boolean a){
change = a;
repaint();
}
public Dimension getPreferredSize(){
int size = (radius+border)*2;
return new Dimension( size, size );
}
public void paintComponent(Graphics g){
g.setColor( Color.black );
g.fillRect(0,0,getWidth(),getHeight());
if (change){
g.setColor( on );
} else {
g.setColor( on.darker().darker().darker() );
}
g.fillOval( border,border,2*radius,2*radius );
}
}
发布于 2018-10-21 06:49:52
在绿色边框中添加,
向面板添加边框。阅读How to Use Borders上的Swing教程
使灯光居中
最简单的方法是为您的交通信号灯面板使用“包装器”面板:
//getContentPane().add(p1);
JPanel wrapper = new JPanel();
wrapper.add( p1 );
add( wrapper );
JPanel
的默认布局是FlowLayout
居中对齐。因此,当帧大小改变时,交通信号灯将保持居中。
将按钮移动到灯的顶部
不要使用GridLayout。默认情况下,JFrame使用BorderLayout
。只要使用该布局即可。请阅读How to Use BorderLayout上的Swing教程,以确定应对每个面板使用哪个约束。
https://stackoverflow.com/questions/52907555
复制相似问题