【发布时间】:2014-01-05 11:09:00
【问题描述】:
我一直在创建一个系统,通过它我可以在 GUI 中列出火车上的各种座位。我决定使用一个简单的网格布局,其中编号的 JButtons 代表座位,而 seatNo 和空的 JLabels 代表空的空间(我意识到这可能是微不足道的,但它很简单)。我使用了 Gridlayout,并创建了如下所示的按钮和标签。
我在一个单独的类中有一个列表 (compArray2),它由 0 和 1 和一个方向组成,该方向表示应该有座位和不应该有座位的位置。 .getNum 获取值为 0 表示空白空间或 1 表示座位,.getDir 获取座位将面对的方向。
public JPanel rowPanelCreation(int type, int rowNo, int width){
theNoOfSeats=0;
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0,width));
List<seatLayout> layout = new ArrayList<>();
layout = ModelConstants.compArray2;
for (seatLayout isit : x2){
buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
buttonDis = new JLabel();
if (isit.getNum()==0){
if (isit.getDir()=='x'){
panel.add(buttonDis);
}
}
else if (isit.getNum()==1){
theNoOfSeats++;
if (isit.getDir()=='N'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultN.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
else if (isit.getDir()=='E'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultE.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
buttonEna.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){JOptionPane.showMessageDialog(null,"You have chosen : ");}});
panel.add(buttonEna);
}
else if (isit.getDir()=='S'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultS.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
else if (isit.getDir()=='W'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultW.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
}
}
return panel;
}
我遇到的主要问题是,当我按下其中一个座位按钮时,我希望出现一条消息,告诉我我选择的座位的座位号是。但是,当我这样做时,它只会显示最后一个座位号。有没有更好的方法可以做到这一点?我假设所有按钮都基本相同,所以没有办法区分它们?
【问题讨论】:
-
这段代码所做的就是创建按钮。如果您在执行某些操作时遇到问题,显示您的
actionPerformed不是很重要吗?或者这是您认为错误发生的地方? -
@peeskillet 现在可以使用了,谢谢您的帮助。