Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I hava a class StageDAO like this:
public class Stage{
public int stageID;
public String label;
public Stage(ResultSet rs) {
try{
this.stageID=rs.getInt("StageID");
this.label=rs.getString("Label");
}
catch(Exception e){}
}
}
I have a method in a class StageDAO, where i get Data from Database, like this:
public class StageDAO{
Connect connectdb;
public StageDAO(Connect connectdb){
this.connectdb=connectdb;
}
public Vector retrieveAll() {
ResultSet lobjRS=null;
Vector lobjList=new Vector();
Connection lobjConnection = null;
Statement lobjStatement=null;
Stage lobjStage = null;
try{
lobjConnection = this.connectdb.getConnection();
lobjStatement = lobjConnection.createStatement();
lobjRS = lobjStatement.executeQuery(
"SELECT * FROM Stage order by sortkey");
while(lobjRS.next()){
lobjStage = new Stage (lobjRS);
lobjList.add(lobjStage);
}
}catch(){}
}
}
in my GUi class i have this:
StageDAO lobjStage= new StageDAO (connectdb);
Vector<Stage> stageList = lobjStage.retrieveAll();//Here i have the information
of stageID and stagelabel
private JComboBox lcbstage;
public void initialize(){
lcbstage= new JComboBox();
for(int i=0; i<stageList .size();i++){
lcbstage.addItem(stageList.get(i).label);
}
}
But know if i select in my Gui the stage, i want to know the stageid.
I don't know how to get the stageid of the selected stagelabel ?
Thank you for your help.
Add the whole item to your JComboBox, not just the label, and create a toString() method which will return just the label:
public String toString(){
return this.label;
}
JComboBox's addItem takes an object and then converts it to a string for display, so when you do getSelectedItem() the whole object, id and label and everything else, will be returned.
public void initialize(){
lcbstage= new JComboBox();
for(int i=0; i<stageList .size();i++){
lcbstage.addItem(stageList.get(i));//this line changed
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to create a Java program that manage a booking ticket system.
I have a film Class:
public class Film {
private String title;
private Double price;
private String ageRestriction;
private double rating;
private String genre;
private String location;
private String screenDay;
A FilmList Class that create an ArrayList of Films item and sort, based by two parameters (Location and Week)
public class FilmList {
public FilmList(ArrayList<Film> filmArrayList) {
this.filmArrayList = filmArrayList;
}
public FilmList (){
this.filmArrayList = new ArrayList<>();
}
public ArrayList <Film> filmArrayList;
public void addFilm(Film films){
this.filmArrayList.add(films);
}
private String showLocation;
private String screenWeek;
public void setScreenWeek(String screenDay) {
this.screenWeek = screenDay;
}
public String getScreenWeek() {
return screenWeek;
}
public void setShowLocation(String location) {
this.showLocation = showLocation;
}
public String getShowLocation() {
return showLocation;
}
public Optional<Film> searchFilm(){
Optional<Film> movieFounded = filmArrayList.stream().filter(i -> i.getLocation().contains(getShowLocation()) &&
i.getScreenDay().contains(getScreenWeek())).findAny();
return movieFounded;
}
The setShowLocation parameter it's stetted by the click of a button (there's one of them for each theatre, and the setScreenWeek it's stetted by a Combobox
the Graphic unit interface with the console. Notice that if I press the button without select anything on the combobox I got an error.
So
FilmList filmList = new FilmList();
filmList.addFilm
System.out.println(searchFilm().toString());
Your code is a bit strange, but I suppose you meant passing a Film instance to addFilm, and then using filmList.searchFilm().
Anyway
filter(
i -> i.getLocation().contains(getShowLocation()) &&
i.getScreenDay().contains(getScreenWeek())
)
Here you're filtering the filmArrayList, which contains a single element at that point. And
i.getLocation().contains(getShowLocation())
means basically
i.getLocation().contains(null)
as the showLocation field isn't initialized.
The same applies for the second condition, using screenWeek.
I'm actually surprised it doesn't throw a NullPointerException, as
public boolean contains(CharSequence s) {
return indexOf(s.toString()) > -1; // NullPointerException at s.toString()
}
But anyway, let's say you initialized those fields, then the only element is discarded by the filter operation, that's why you see Optional.empty.
final FilmList filmList = new FilmList();
filmList.setShowLocation("Your location");
filmList.setScreenWeek("Screen week");
filmList.addFilm(filmInstance);
System.out.println(filmList.searchFilm().toString());
You obviosly need a fully constructed Film instance
final Film filmInstance = new Film();
filmInstance.title = "The NullPointerException adventure";
filmInstance.price = 12D;
filmInstance.ageRestriction = "+18";
filmInstance.rating = 18D;
filmInstance.genre = "Horror";
filmInstance.location = "US";
filmInstance.screenDay = "Monday";
filmList.addFilm(filmInstance);
The problem is in the FilmList#setShowLocation method.
You're assigning showLocation to itself, and the location parameter is unused.
public void setShowLocation(String location) {
this.showLocation = showLocation;
}
This should be
public void setShowLocation(String location) {
this.showLocation = location;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
i'm new to Java and I'm trying to write a code that Scan for some Patients' names, also ask them to enter (y/n) if they are allergicToGluten, and then I print out a list of name of all the patients that are allergicToGluten. I just learnt Arrays but i'm still struggling in assigning many values ( name + y/n ) to an Array. I need your help.
Thank you very much :D
You need to create a class that represents your patient. And then you can have array of patients
public class Patient{
private String name;
private boolean allergicToGluten;
public Patient(String name, boolean allergicToGluten){
this.name = name;
this.allergicToGluten = allergicToGluten;
}
public boolean isAllergicToGluten(){
return allergicToGluten;
}
public String getName(){
return name;
}
}
----
Patient[] patients = new Patient[patientCount];
If you don't know patientCount then you need resizable-array.
ArrayList<Patient> patients = new ArrayList<Patient>();
// ... reading 'name' and 'isAllergic' from input
patients.add(new Patient(name, isAllergic));
And then you can print list of allergic patients
for(p : patients){
if (p.isAllergicToGluten())
System.out.println(p.getName());
}
There is no way to allocate more than one value to an array, but you can make an array of some class with multiple fields in it. For example,
public class Patient {
public String name;
public boolean isAllergic;
public Patient(String name, boolean isAllergic) {
this.name = name;
this.isAllergic = isAllergic;
}
}
public class Patient_Driver {
public static void main(String[] args) {
Patient[] patients = new Patient[] {
new Patient("Steve", true),
new Patient("Mary", false)
};
for (int i = 0; i < patients.length; i++) {
if (patients[i].isAllergic) {
System.out.println(patients[i].name);
}
}
}
}
Output:
Steve
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a quick question
Suppose I were to create a data definition class named Campaign
and then I want to make an implementation class
Let's say in this implementation class I have a few variables(campaignName, campaignType, campaignGoal) and some methods (getCampName, getCampType, getCampGoal).
I want to create two different campaigns classes, and then compare their information at the end of the program with a print method.
Would this be a proper way of declaring information for the first campaign:
Campaign campaign1 = new Campaign();
which is in the main method, and then let's say I want to get the name of the first campaign, which is just hardcoded for now
public static String campaign1.getCampName(){
campaign1.setCampName("IT Student Scholarship Fund");
}
I just wanted to know how to do this. Thank you.
getCampName() should look something like:
public String getCampName() { return this.campaignName; }
a then simply
campaign1.getName();
You should stop the practice of putting all of your code in a main method. Instead, instantiate your Campaign instances and call methods on each one using a driver method in your primary class. In addition, you can override the equals() method to do the comparison (or implement Comparator).
public class CampaignTest{
public void runTest(){
Campaign c1 = new Campaign("First Campaign");
Campaign c2 = new Campaign("Second Campaign");
Campaign c11 = new Campaign("First Campaign");
System.out.println("c1==c2: " + c1.equals(c2));
System.out.println("c2==c11: " + c2.equals(c11));
System.out.println("c1==c11: " + c1.equals(c11));
}
public static void main(String... args){
CampaignTest test = new CampaignTest();
test.runTest();
}
private class Campaign{
private String name;
public Campaign(String n){
this.name = n;
}
public String getName(){
return name;
}
#Override
public boolean equals(Object other){
if(other instanceof Campaign && ((Campaign)other).getName().equals(name)){
return true;
}
return false;
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I've a problem with my ActionListener. When I launch my application a NullPointerException appears.
This is the code :
public class SimulationPopUp extends javax.swing.JFrame {
private String simulation;
private Data d;
/**
* Creates new form SimulationPopUp
*/
public SimulationPopUp(String simulation, Data d) throws SQLException, IOException {
this.simulation=simulation;
this.d = d;
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
initComponents();
simulationChosen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
changeSimulation(e);
}
});
simulationChosen.removeAllItems();
try {
Object[] o = d.ExtractAllSimulation(simulation);
for (int i=0; i<o.length-1; i++){
simulationChosen.addItem(o[i]);
}
Object[] param = d.ExtractAllParameters((int)o[o.length-1]);
jLabel25.setText((String)param[0]);
jLabel26.setText(""+(Double)param[1]);
jLabel27.setText(""+(Integer)param[2]);
jLabel28.setText(""+(Integer)param[3]);
jLabel29.setText(""+(Double)param[4]);
jLabel30.setText(""+(Integer)param[5]);
jLabel31.setText(""+(Integer)param[6]);
jLabel32.setText(""+(Integer)param[7]);
jLabel33.setText(""+(Integer)param[8]);
jLabel34.setText(""+(Integer)param[9]);
jLabel35.setText(""+(Double)param[10]);
jLabel36.setText(""+(Integer)param[11]);
jLabel37.setText(""+(Double)param[12]);
jLabel38.setText(""+(Integer)param[13]);
jLabel39.setText(""+(Integer)param[14]);
jLabel40.setText(""+(Integer)param[15]);
jLabel41.setText(""+(Integer)param[16]);
jLabel42.setText(""+(Double)param[17]);
jLabel43.setText(""+(Integer)param[18]);
jLabel44.setText(""+(Integer)param[19]);
jLabel45.setText(""+(Integer)param[20]);
jLabel46.setText(""+(Integer)param[21]);
}catch(SQLException e) {
Logger.getLogger(SimulatorGui.class.getName()).log(Level.SEVERE, null, e);
}
}
private void changeSimulation(java.awt.event.ActionEvent e) {
String run = simulationChosen.getSelectedItem().toString();
System.out.println(run);
ImageIcon image = new ImageIcon("../charts/"+simulation+"/"+run+"/chart.png");
JLabel label = new JLabel(image);
label.setSize(imagePanel.getWidth(), imagePanel.getHeight());
imagePanel.add(label);
imagePanel.repaint();
}
}
Can you help me please?
By default, no item is selected on simulationChosen. Select an item in initComponents or before the ActionListener is created.
simulationChosen.setSelectedIndex(0)
Be sure that the simulationChosen has items to be selected inside.
You add an ActionListener, that calls the changeSimulation(), the first string in this method is simulationChosen.getSelectedItem()
But right after You added an ActionListener in the next line You call simulationChosen.removeAllItems();
What happens when event is fired and simulationChosen has no elements? It's your NullPointer.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have ArrayList and protected getter function in first class and function in second class, which extends first class. I do getList().size() in function, but getting 0. If I do myList.size() in first class, I getting right answer.
Code:
protected List<WrappedGameProfile> getList(){
return Text;
}
public int getServerInfoSize(){
return super.getList().size(); //returns 0
}
All code:
package ServerInfo;
//imports
public class ServerInfo extends JavaPlugin {
Logger log;
private List<WrappedGameProfile> Text = new ArrayList<WrappedGameProfile>();
FileConfiguration config;
protected String ConvertFormat(String format){
return format.replace("#0", ""+ChatColor.BLACK).replace("#1", ""+ChatColor.DARK_BLUE).replace("#2", ""+ChatColor.DARK_GREEN).replace("#3", ""+ChatColor.DARK_AQUA).replace("#4", ""+ChatColor.DARK_RED).replace("#5", ""+ChatColor.DARK_PURPLE).replace("#6", ""+ChatColor.GOLD).replace("#7", ""+ChatColor.GRAY).replace("#8", ""+ChatColor.DARK_GRAY).replace("#9", ""+ChatColor.BLUE).replace("#a", ""+ChatColor.GREEN).replace("#b", ""+ChatColor.AQUA).replace("#c", ""+ChatColor.RED).replace("#d", ""+ChatColor.LIGHT_PURPLE).replace("#e", ""+ChatColor.YELLOW).replace("#f", ""+ChatColor.WHITE);
}
protected List<WrappedGameProfile> getList(){
return Text;
}
protected void setText(List<WrappedGameProfile> Text){
this.Text = Text;
}
public void onEnable(){
log = getLogger();
log.info("GuiServerInfo activating...");
this.saveDefaultConfig();
config = getConfig();
ProtocolLibrary.getProtocolManager().addPacketListener(
new PacketAdapter(this, ListenerPriority.NORMAL,
Arrays.asList(PacketType.Status.Server.OUT_SERVER_INFO), ListenerOptions.ASYNC) {
#Override
public void onPacketSending(PacketEvent event) {
handlePing(event.getPacket().getServerPings().read(0));
}
}
);
for (int i = 0; i < config.getStringList("Text").size();i++){
Text.add(
new WrappedGameProfile(
"id" + i + 1,
ConvertFormat(config.getStringList("Text").get(i)))
);
}
log.info("GuiServerInfo active!");
}
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender.isOp()){
if (args.length > 0){
if (args[0].equalsIgnoreCase("set")){
Text.clear();
List<String> newConf = new ArrayList<String>();
for (int i = 1; i < args.length; i++){
Text.add(new WrappedGameProfile("id" + Text.size() + 1, ConvertFormat(args[i])));
newConf.add(args[i]);
log.info("Add ServerInfo: " + args[i]);
}
config.set("Text", newConf);
sender.sendMessage("Successful!");
return true;
}
}
return false;
} else {
sender.sendMessage("You not op!");
return true;
}
}
private void handlePing(WrappedServerPing ping) {
ping.setPlayers(Text);
}
public void onDisable(){
saveConfig();
log.info("GuiServerInfo disabled!");
}}
And:
package ServerInfo;
import java.util.ArrayList;
import java.util.List;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
public class ServerInfoAPI extends ServerInfo {
public void setServerInfo(List<WrappedGameProfile> Text){
super.setText(Text);
super.log.info("Set new ServerInfo");
}
public void setServerInfo(String[] Text){
List<WrappedGameProfile> tmp = new ArrayList<WrappedGameProfile>();
for (int i = 0; i < Text.length; i++) {
tmp.set(i, new WrappedGameProfile("id" + i + 1, ConvertFormat(Text[i])));
}
super.setText(tmp);
super.log.info("Set new ServerInfo");
}
public void insertServerInfoString(String str, int num){
getList().set(num, new WrappedGameProfile("id" + num, ConvertFormat(str)));
super.log.info("Add new ServerInfo - num:" + num + ", Text:" + str);
}
public void addServerInfoString(String str){
super.getList().add(new WrappedGameProfile("id" + super.getList().size() + 1, ConvertFormat(str)));
super.log.info("Add new ServerInfo: " + str);
}
public int getServerInfoSize(){
return super.getList().size();
}
public String getServerInfoString(int num){
return super.getList().get(num).getName();
}
public int getServerInfoStringNum(WrappedGameProfile pr){
return super.getList().indexOf(pr);
}
}
Just your terminology alone shows a serious lack of understanding of things like Objects, Classes, Packages, etc. you need to read up on some introductory tutorials.
To answer the question it sounds like you have created a new instance inheriting from a super class. Because it is a new instance the list is not shared, so changes you make in one class do not get seen.
To share one list between multiple objects you need to pass the list object from one to another.
Don't try to globalize variables. Instead call public methods of the class that holds the variable that will allow other objects to query its state or make controlled change to its state.
I agree also with the others: it sounds as if you're misusing inheritance, since this is not a problem that should be solved with inheritance, but only your code (which we haven't seen at the time of this writing) will tell us for sure.
Regarding:
No, i have just one List
No, if you're using inheritance, then you have more than one List. Again don't try to solve this with inheritance.
Why don't you have a
private List<WrappedGameProfile> text = new ArrayList<WrappedGameProfile>();
public List<WrappedGameProfile> getText() {
return text;
}
in your super class?
than your code will be :
public int getServerInfoSize(){
return getText().size();
}
and please do camelcasing correct, the variable Text has to be text.