我正试图用Swing创建一个电影院大厅。因此,为此,我创建了一个Seat
的课程JLabel
:
public class Seat extends JLabel{
public boolean isVip() {
return vip;
}
public boolean isHandicap() {
return handicap;
}
public boolean isOccupato() {
return occupato;
}
public void setVip(boolean vip) {
this.vip = vip;
}
public void setHandicap(boolean handicap) {
this.handicap = handicap;
}
public void setOccupato(boolean occupato) {
this.occupato = occupato;
}
private int x;
private int y;
private boolean vip;
private boolean handicap;
private boolean occupato;
public Seat(int x, int y, ImageIcon img) {
this.x = x;
this.y = y;
this.setIcon(img);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
我想用这个班级在大厅里画座位,并且动作听众在点击时改变座位颜色。
但是当我尝试在GridLayout
的面板中添加座位时,座位会显示在另一个面板上。
public class PanelAddHall extends JPanel {
private int x=5;
private int y=5;
private ArrayList<Seat> seats = null;
public PanelAddHall(Controller_Gestore controller, final JLabel outputGrafico) {
seats = new ArrayList<>();
this.setBackground(Color.GRAY);
this.setLayout(new BorderLayout(10,30));
JPanel nord = new JPanel();
JPanel sud = new JPanel(new GridLayout(x,y,0,5));
JPanel west = new JPanel();
nord.setBackground(Color.GRAY);
sud.setBackground(Color.GRAY);
west.setBackground(Color.GRAY);
ImageIcon seat_icon = new ImageIcon("immagini/poltrone/seat_disponibile.png");
ImageIcon screen_icon = new ImageIcon("immagini/poltrone/screen.png");
JLabel screen = new JLabel(screen_icon);
nord.add(screen);
for(int i = 0; i<x; i++){
for(int j=0; j<y; j++){
seats.add(new Seat(i,j,seat_icon));
}
}
for(int i = 0; i<x*y ; i++) {
sud.add(seats.get(i));
}
this.add(nord, BorderLayout.NORTH);
this.add(sud, BorderLayout.SOUTH);
this.add(west, BorderLayout.WEST);
}
抱歉我的英语不好!
答案 0 :(得分:2)
问题在于,您正在覆盖班级JComponent
中的getX
方法getY
和Seat
。
如果您需要用于预留的坐标,请更改这些方法名称。
我已经创建了这个简单的GUI来测试你的类(使用不同的图像),如果对这两个方法进行了评论,它就可以正常工作。
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SimpleFrameTest2 extends JFrame {
public SimpleFrameTest2() {
setSize(500, 500);
setTitle("Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
initComponents();
setVisible(true);
}
private void initComponents() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 5, 0, 5));
ImageIcon seat_icon = new ImageIcon("C:\\Users\\Ricardo\\Pictures\\referencias\\seating-chart.png");
for (int i = 0; i < 25; i++) {
//panel.add(new JLabel("" + i, seat_icon, JLabel.CENTER));
panel.add(new Seat(i, i, seat_icon));
}
add(panel);
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleFrameTest2();
}
});
}
}
EDITED: 这是我用过http://www.marcuscenter.org/wp-content/uploads/2013/02/seating-chart.png
的图片答案 1 :(得分:1)
您正在覆盖JComponent getX()getY()方法,这会阻止JPanel正确布局标签