【发布时间】:2018-04-07 01:51:06
【问题描述】:
我有一个有 4 个私有属性的类,通过一个 JComboBox 选择,我想通过调用一个过程来修改它们。但是,似乎即使 JComboBox 与选择一起出现,显示的属性也不会改变。
public class PanneauVehicule extends JPanel {
private String[] vehicules;
private int majCarburant;
private int majPassager;
public class PanneauVehicule extends JPanel {
//Main constructor
public PanneauVehicule(){
//Creates a JPanel
super();
//Sets layout as BorderLayout
setLayout(new BorderLayout());
initListeVehicule();
initLabels();
}
public void initListeVehicule(){
vehicules = new String[] {Constantes.CS100 , Constantes.CS300 ,
Constantes.GREYHOUND102D3 , Constantes.GREYHOUNDG4500 ,
Constantes.TGVATLANTIQUE , Constantes.TGVDUPLEX};
final JComboBox<String> vehiculesList = new JComboBox<>(vehicules);
//Keep in mind the comboBox does appear with the right selections
add(vehiculesList,BorderLayout.NORTH);
//Here's where it doesnt work.
vehiculesList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
majInfo(2,4);
}
});
}
public void majInfo(int test1, int test2){
this.majCarburant = test2;
this.majPassager = test1;
}
public void initLabels(){
JPanel panneauBas = new JPanel();
panneauBas.setLayout(new GridLayout(2,1,5,5));
JLabel labelCarburant = new JLabel();
labelCarburant.setText("Type de caburant: " + this.majCarburant);
JLabel labelPassagers = new JLabel();
labelPassagers.setText("Nb de passagers: " + this.majPassager);
panneauBas.add(labelPassagers);
panneauBas.add(labelCarburant);
add(panneauBas, BorderLayout.SOUTH);
panneauBas.setBackground(Color.WHITE);
}
之后,我使用另一个程序使 majCarburant 和 majPassager 出现在屏幕上。但是,它们的值显示为默认值 (0)。我可以在不使用 ActionListener 的情况下手动更改它们的值,但手头的任务需要我使用一个。
【问题讨论】:
-
您的代码所做的只是更新 majCarburant 和 majPassager 变量的值。变量不显示在屏幕上。您需要使用新值更新 Swing 组件。由于您似乎在 GUI 上使用 JLabels,因此您需要使用
setText(...)方法来更改标签的显示。如果您需要更多帮助,并且将来当您提出问题时,请发布适当的 minimal reproducible example 来说明问题。 -
我提到我使用了一个函数,它通过 JLabels 和 setText 在屏幕上显示值。我认为没有必要添加它,但它基本上是 initLabels();一开始就叫。由于字数限制,我放不下。
-
initLables()在您创建 GUI 时使用。当您要更改标签中显示的值时,它与此无关。 您需要在标签上调用 setText() 方法来更改其值!!!。更改变量的值没有任何作用。 -
I can't fit it in because of character limit- 那是因为您还没有发布MCVE。您的问题是关于在生成 ActionEvent 时更改标签的值。因此,创建一个带有标签的 JFrame 和一个带有 ActionListener 的 JButton。单击按钮时,更改文本。先让它发挥作用,然后将知识应用到您的实际应用程序中。 -
我确实在
initLabels()中调用了 setText。我也在调用initListeVehicule()之后调用此过程。
标签: java swing actionlistener jcombobox