Java使用在动作侦听器中创建的变量 [英] Java using variable created in action listener
问题描述
我在某些Java代码方面遇到问题。我不知道该怎么解决。请注意,该代码非常简化。
I am having issues with some java code. I cannot figure out how to solve it. Please note that the code is heavily simplifed.
在panelQuestion中,我正在创建一个带有按钮和两个组合框的GUI。我在按钮上添加了一个动作监听器。
In panelQuestion, I am creating a GUI with a button and two combo boxes. I add an action listener to the button.
单击此按钮时,将创建一个带有组合框值的字符串,称为objectName。
When this button is clicked, a string with the values of the combo boxes is created, called objectName.
初始化GUI后,我创建对象。
After having initialized the GUI, I create objects.
问题是我希望能够在主类中使用objectName以便检查
The issue is that I would like to be able to use the objectName in the main class so that I can check for some of its attributes.
例如,如果用户选择莱斯特和约克,则将创建字符串(leicester_york),并将该字符串用于检查该对象的属性。
For example, if the user was to choose Leicester and York, the string would be created (leicester_york), and that string would be used to check for that objects attributes.
但是这不起作用。有人告诉我objectName不存在。
However this does not work. I am told that objectName does not exist. Any help would be appreciated, thanks.
panelQuestion:
panelQuestion:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class ThreePanelLayout {
private JComponent ui = null;
private CardLayout cardLayout = new CardLayout();
String objectName;
ThreePanelLayout() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
//create the 3 panels of the '3 panel layout'.
JPanel panel1 = new JPanel(new BorderLayout());//();
panel1.setBackground(Color.RED);
panel1.setBorder(new TitledBorder("Choose Option"));
JPanel panel2 = new JPanel(new BorderLayout());
panel2.setBackground(Color.GREEN);
panel2.setBorder(new TitledBorder("Choose Two Stops"));
JPanel panel3 = new JPanel();
panel3.setBackground(Color.ORANGE);
panel3.setBorder(new TitledBorder("Click an Option"));
panel3.setLayout(cardLayout);
// add the buttons to 1st panel
JButton timeButton, priceButton, routeButton, adminButton, exitButton, inputRoute, saveRoute, retrieveRoute, backToMain; //DECLARING BUTTON
timeButton = new JButton("Time");
priceButton = new JButton("Price");
routeButton = new JButton("Route");
adminButton = new JButton("Admin");
exitButton = new JButton("Exit");
inputRoute = new JButton("Input Route");
saveRoute = new JButton("Save Route");
retrieveRoute = new JButton("Retrieve route");
JPanel panelButtons = new JPanel(new GridLayout(5,1,5,5));
panelButtons.add(timeButton);
panelButtons.add(priceButton);
panelButtons.add(routeButton);
panelButtons.add(adminButton);
panelButtons.add(exitButton);
panel1.add(panelButtons, BorderLayout.LINE_START);
JPanel panelAdmin = new JPanel(new GridLayout(5,1));
JPanel panelAdminSize = new JPanel();
panelAdminSize.add(inputRoute);
panelAdminSize.add(saveRoute);
panelAdminSize.add(retrieveRoute);
panelAdmin.add(panelAdminSize);
// adding the combos to the top of 2nd panel
String stops[] = {"Leicester","Loughborough","Nottingham","Derby","York"};
JComboBox departingStop = new JComboBox();
JComboBox finalStop = new JComboBox();
for(int i = 0; i < stops.length; i++) {
departingStop.addItem(stops[i]);
finalStop.addItem(stops[i]);
}
JPanel panelCombo = new JPanel(new FlowLayout());
panelCombo.add(departingStop);
panelCombo.add(finalStop);
panel2.add(panelCombo, BorderLayout.PAGE_START);
// adding options to panel 3
// panel for when time is clicked
JPanel panelTime = new JPanel (); //creating panel for time option
JLabel timeLabel = new JLabel("The time between x and y is");
panelTime.add(timeLabel);
//panel for when price is clicked
JPanel panelPrice = new JPanel ();
JButton confirmPrice = new JButton("Confirm");
JRadioButton singleRadio = new JRadioButton("Single");
JRadioButton returnRadio = new JRadioButton("Return");
ButtonGroup group = new ButtonGroup();
group.add(singleRadio);
group.add(returnRadio);
panelPrice.add(singleRadio);
panelPrice.add(returnRadio);
panelPrice.add(confirmPrice);
// used for route button
JPanel panelRoute = new JPanel();
JLabel routeLabel = new JLabel ("Stop between X and Y");
panelRoute.add(routeLabel);
JButton sortButton = new JButton("Sort");
panelRoute.add(sortButton);
panel3.add(panelTime,"1");
panel3.add(panelPrice,"2");
panel3.add(panelRoute,"3");
panel3.add(panelAdmin,"4");
timeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cardLayout.show(panel3, "1");
Object comboValue = departingStop.getSelectedItem();
Object combo2Value = finalStop.getSelectedItem();
objectName = comboValue + "_" + combo2Value;
objectName = objectName.toLowerCase();
}
});
priceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cardLayout.show(panel3, "2");
}
});
routeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cardLayout.show(panel3, "3");
}
});
adminButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cardLayout.show(panel3, "4");
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
// assembling panels
panel2.add(panel3);
panel1.add(panel2, BorderLayout.CENTER);
ui.add(panel1);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ThreePanelLayout o = new ThreePanelLayout();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.setSize(600,400);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
Journey leicester_loughborough = new Journey();
leicester_loughborough.setSingleCost(2.5);
Journey leicester_nottingham = new Journey();
leicester_nottingham.setSingleCost(3.5);
Journey leicester_derby = new Journey();
leicester_derby.setSingleCost(3.7);
Journey leicester_york = new Journey();
leicester_york.setSingleCost(23.5);
objectName.getSingleCost(); //error comes up here
}
}
旅程:
public class Journey
{
public double singleCost;
public void setSingleCost(double cost) {
singleCost = cost;
}
public double getSingleCost() {
return singleCost;
}
}
我不认为这个问题是重复的。使用解决方案objectName = this.objectName时,会出现相同的问题。
I don't think this question is a duplicate. When using the solution objectName = this.objectName, the same issue arises.
推荐答案
您需要声明以下内容: String objectName
作为成员变量 panelQuestion 类!
You need to declare this: String objectName
as a member variable of the panelQuestion class!
您需要阅读如何一个对象有效,它们的方法,成员以及它们在做什么。...正如我在上面提到的objectName.getSingleCost()毫无意义,并且没有进行编译,原因是:objectName是 string >对象和字符串没有称为 getSingleCost
you need to read how an object works and what are their methods, members and what are they doing.... as I commented above objectName.getSingleCost() makes no sense, and is not compiling, the reason: objectName is a string object and strings have no method called getSingleCost
的方法,只是因为您这样做:
just because you do:
String objectName;
Object comboValue = departingStop.getSelectedItem();
Object combo2Value = finalStop.getSelectedItem();
objectName = comboValue + "_" + combo2Value;
dosnt表示现在objectName从字符串突变为ComboBox ...
dosnt mean that now objectName mutated from string into a ComboBox...
相同是无效的:
Car tata = new Car();
Robot kuka = new Robot();
String foo = tata.getName() + kuka.getName();
现在什么是foo?变压器? 否,仍然是一个字符串...
now what is foo? a transformer?? NO, is still a String...
您可以找到成千上万的教程...进行搜索,阅读,学习,然后再走一步。 ...
you can find thousands of tutorials... go search, read, learn and go 1 step after the other....
这篇关于Java使用在动作侦听器中创建的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!