JComponent name cannot be resolved, when used in another method - java

I'm following a youtube tutorial (http://www.youtube.com/watch?v=wpbQ0DCFF0M) to populate a JCombobox called "comboAccountName" with a database table.
My database connection is setup in another class.
The code is as follows -
public class Execute extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
//---------------------------------------------------------------------------------------------------------------------
public Execute()
{
.............other code...............
JComboBox comboAccountName = new JComboBox();
comboAccountName.setBounds(313, 31, 302, 20);
getContentPane().add(comboAccountName);
.............other code...............
}
void PopulateJCB()
{
String queryString = "SELECT DISTINCT [Account Name] FROM main ORDER BY [Account Name]";
try
{
Connection statJCBaccountname = DatabaseConnection.ConnectDB();
Statement stmt = statJCBaccountname.createStatement();
ResultSet rsJCBaccountname = stmt.executeQuery(queryString);
while (rsJCBaccountname.next())
{
comboAccountName.addItem(rsJCBaccountname.getString(1));
System.out.println(rsJCBaccountname.getString(1));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Execute frame1 = new Execute();
frame1.setVisible(true);
PopulateJCB();
}
There are 2 errors where I'd like your help
comboAccountName cannot be
resolved
occurs inside the while loop, at following line
comboAccountName.addItem(rsJCBaccountname.getString(1));
AND
Cannot make a static reference to the non-static method PopulateJCB() from the type
Execute
occurs when I'm trying to call PopulateJCB(); in the main method
I know the code in the tutorial video isn't exactly the same, but I'm trying to do a similar thing here. Please help.

Scope! You declare your comboAccountName inside of the constructor and so it is visible only inside of the constructor. Try to use it elsewhere and it fails. Solution: declare it outside of the constructor on the class level.
So not:
public class Execute extends JFrame {
public Execute()
{
JComboBox comboAccountName = new JComboBox(); // this guy is visible only in here
comboAccountName.setBounds(313, 31, 302, 20); // don't do this!
getContentPane().add(comboAccountName);
}
but rather:
public class Execute extends JFrame {
private JComboBox comboAccountName = new JComboBox();
public Execute()
{
comboAccountName.setBounds(313, 31, 302, 20);
getContentPane().add(comboAccountName);
}
Next we'll talk about your use of null layouts, setBounds(...) and absolute positioning. While to a newbie this seems the best way to create complex GUI's, the more you deal with Swing GUI creation, the more you will find that doing this will put your GUI in a straight-jacket, painting it in a very tight corner and making it very hard to extend or enhance. Just don't do this.
As for this error:
Cannot make a static reference to the non-static method PopulateJCB() from the type
You must create an instance of the class and call the method on the instance, not on the class itself.
So not:
public static void main(String[] args) {
// TODO Auto-generated method stub // please clean your code of this before posting here
Execute frame1 = new Execute();
frame1.setVisible(true);
PopulateJCB();
but:
public static void main(String[] args) {
Execute frame1 = new Execute();
frame1.setVisible(true);
frame1.PopulateJCB(); // call it on the Execute instance, frame1

Related

how to solve java.lang.NullPointerException for array assignment

I am trying to assign a variable from SQL result to array element but it keeps showing me java.lang.NullPointerException. I tried to declare the array above but it seems not working. The exception doesn't show the line of the error but I write print statements to figure out the exception place then I found out that when I print the value of the activity[i] it equals null.
Here is the code:
package main;
import java.awt.EventQueue;
public class ACTIVITY {
private Connection con;
private Statement stm;
private String sql;
private ResultSet rs;
private static int c_id=-1;
private static int s_id=-1;
private int a_id=-1;
private String activity[]=new String[5];
private int activityID[] =new int[5];
public static JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ACTIVITY window = new ACTIVITY();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ACTIVITY() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
panel.setVisible(true);
try {
Class.forName("com.mysql.jdbc.Driver");
con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","****" , "********");
stm= con.createStatement();
sql="Select * from activity where sid="+s_id;
rs=rs=stm.executeQuery(sql);
String name=" ";int i=0;
while(rs.next()){
name=rs.getString("a_name");
a_id=rs.getInt("a_id");
activity[i]=name;//after this assignment it always equal null
activityID[i]=a_id;
i++;
}
//the rest of the code
con.close();
} catch(Exception e) {System.out.println(e); }
}
}
Personally, I'd suggest using ArrayList instead of an array for this, but that's just personal preference. Here's an article on that https://www.w3schools.com/java/java_arraylist.asp
As far as the issue as you have it, the problem is you have a declared a private string array and are trying to assign values to it in another method. The array is populating with default values of null since it's a String array. The reason you're getting the exception is because it's returning this default value rather than your assigned value.
You can still use a private array, but you'll want to declare it as static and use a static method to add a value to it. That way, when you add the value to it, it'll be returnable the way you expect. This is a much simpler example, but shows how to achieve this:
public class Test {
private static String activity[] = new String[5];
public void addValue() {
activity[0] = "Yo";
}
public static void main(String[] args) {
Test test = new Test();
test.addValue();
System.out.println(activity[0]);
}
}
As for your specific code, I would suggest declaring both activity[] and activityID[] as static arrays. Then, you will need to create an object in your main method to call your value. Your changes would look like this:
private static String activity[] = new String[5];
private int activityID[] =new int[5];
Then in your main method, add:
window.initialize(); //where window is your class object you declared
That will get you the result you want. I'd also suggest renaming your method you called the same thing as your class.

Java Alter Swing Element from Child Class

I'm having a problem with something I don't understand. I have a java class that is building up my program and another class full of functions called by action listeners.
I'm hoping to use the the child's class functions to alter the contents of a JLabel (just an example) using a setter function which doesn't seem to be doing anything and not crashing.
My main class has
public class Parent extends JFrame {
static JPanel dummyPanel = new JPanel();
static JLabel dummyLabel = new JLabel("label");
static JButton dummyButton = new JButton("button");
static Child child = new Child();
public Parent() {
// main setup goes here
// add elements goes here
ActionListener alterLabel = new ActionListener() {
public void actionPerformed(ActionEvent dummyButton) {
child.childFunc();
}
}
dummyButton.addActionListener(alterLabel);
}
// main function goes here
public void newText() {
dummyLabel.setText("altered");
System.out.println("new text function has been executed");
}
}
Then the child I am using to call the function to change the text contains
public class Child {
public void childFunc() {
Parent parent = new Parent();
parent.newText();
}
}
When I click the button it runs and I see it outputs the string which I expect but it does not seem to change the label.
Why is this and is there a way to fix it?

Java - Cannot find the symbol of an inner class that implements an ActionListener

I'm going off of what I saw in a textbook to make an action listener for a button. To do it, I made an inner class. When I try to call the inner class, the error comes up: cannot find symbol.
Here's the code:
package GUI;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ATMGUI extends GUI
{
public ATMGUI()
{
this.makePane();
this.makeButton("Withdraw");
button.addActionListener(new WithdrawListener());
pane.add(button);
this.makeText("Enter amount to withdraw: ");
pane.add(text);
this.makeTextField("Enter amount here");
pane.add(field);
this.makeFrame();
frame.add(pane);
class WithdrawListener implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
System.out.println("This is a test.");
}
}
}
//------------------------------------------------------------------
public void makeFrame()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
public void makePane()
{
pane = new JPanel();
pane.setLayout(new GridLayout(3,3));
pane.setVisible(true);
}
public void makeButton(String buttonName)
{
button = new JButton(buttonName);
}
public void makeText(String addText)
{
text = new JLabel(addText);
}
public void makeTextField(String addText)
{
field = new JTextField(addText);
}
}
This is the particular bit that is giving me trouble
button.addActionListener(new WithdrawListener());
I saw somewhere else that it had to be instantiated in a certain way.
I tried something like:
ATMGUI a = new ATMGUI();
ATMGUI.WithdrawListener w = a.new WithdrawListener();
and then put w in for the argument, but that didn't really work for me either.
Not sure if it is because I'm working in a subclass. Also not really sure if things need to be done differently because I'm working with an interface.
Place the WithdrawListener outside of the constructor context
public class ATMGUI extends GUI {
public ATMGUI() {
//...
button.addActionListener(new WithdrawListener());
//...
}
class WithdrawListener implements ActionListener {
public void actionPerformed(ActionEvent click) {
System.out.println("This is a test.");
}
}
Add listener to button after local class declaration.
public void abc(){
PQR pqr = new PQR(); // incorrect
class PQR {
}
}
Correct way is
public void abc(){
class PQR {
}
PQR pqr = new PQR(); //correct
}
It seems like you must declare the local class before you use it. The follwing code snippets I tested:
This one showed no errors:
public void testFunc() {
class Test {
}
Test test = new Test();
}
But this one does:
public void testFunc() {
Test test = new Test();
class Test {
}
}
Edit: Sorry for posting nearly at the same time, next time I will check three times if someone already posted.
Use of anonymous type is recommended when you are not reusing a class.
Have a look at it (frequently used with listeners) - It's a great answer!!
quoted from above link
Using this method makes coding a little bit quicker, as I don't need
to make an extra class that implements ActionListener -- I can just
instantiate an anonymous inner class without actually making a
separate class.
I only use this technique for "quick and dirty" tasks where making an
entire class feels unnecessary. Having multiple anonymous inner
classes that do exactly the same thing should be refactored to an
actual class, be it an inner class or a separate class.
this.makePane();
this.makeButton("Withdraw");
button.addActionListener(new ActionListener() { //starts here
public void actionPerformed(ActionEvent click)
{
System.out.println("This is a test.");
}
});//ends
pane.add(button);
this.makeText("Enter amount to withdraw: ");
pane.add(text);
this.makeTextField("Enter amount here");
pane.add(field);
this.makeFrame();
frame.add(pane);

java Passing variables from one class to another

I have an error for the code below. Sorry if this is too basic as I am new to java.
Basically, I cannot retrieve the String "44418" from the class CityChange.
I know the reason is because I created a new instance cc in the class MainPanel.
However I do not know any other way of doing it.
public class CityChange extends JPanel {
public CityChange() {
JButton btn1 = new JButton("London")
this.add(btn1);
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//London Yahoo Weather Code 44418
setCitySelected("44418");
}
});
}
public void setCitySelected(String citySelected) {
this.citySelected = citySelected;
}
public String getCitySelected() {
return citySelected;
}
private String citySelected;
}
public class MainPanel extends JPanel {
public MainPanel() {
CityChange cc = new CityChange();
System.out.println(cc.getCitySelected()); //returns null instead of 44418
}
}
Please give some advice. Thank you.
For timing reasons, the value has no choice but to be null.
What happens here "immediately" (at init time) is that a new CityChange object is created and its citySelected is gotten and printed. As nobody set it otherwise, it is null.
Only after firing the event (clicking the button), it gets a value, and if you print the value then, you'll see the new value.
The code setCitySelected("44418"); is only executed when you call the method public void actionPerformed(ActionEvent evt) which is not happening at the moment. This Method is only called via a Button in a GUI so you first need at least a simple Window with a Button. Here is a good example http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

My method to load the html from a url in a web browser does not work

I am trying to make a web browser for the fun of it, i seem to get errors when ever i put in my loadHtml method, when i comment that out everything works even the action listener.
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.applet.*;
public class browserPannel extends JFrame{
public static void main(String[] arg) {
JFrame browser = new JFrame("A Nun In A Weelchair");
browser.setSize(1000,700);
browser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
browser.setLocationRelativeTo(null);
JPanel header = new JPanel();
header.setBackground(Color.lightGray);
JTextField url = new JTextField(20);
url.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
//loadHtml(event.getActionCommand);
System.out.println("action performed");
}
}
);
url.setSize(890,30);
url.setVisible(true);
JButton send = new JButton("Send");
send.setSize(75,30);
send.setVisible(true);
JEditorPane htmlc = new JEditorPane();
htmlc.setBackground(Color.red);
htmlc.setEditable(true);
htmlc.setContentType("text/html");
header.add(url, BorderLayout.SOUTH);
header.add(send);
browser.getContentPane().add(header, BorderLayout.NORTH);
browser.getContentPane().add(new JScrollPane(htmlc));
browser.pack();
browser.setVisible(true);
}
private void loadHtml(String link)
{
try{
//htmlc.setPage(link);
//url.setText(link);
}catch(Exception e){
System.out.println("ops sorry could not fined Virgine Mobile");
}
}
}
from what i can tell it looks like it can not recognize the url and the htmlc
I have tried to comment the htmlc.setPage and the url.setText, and when i do that my program compiles.
why am i getting these errors, shouldn't it recognize that they are defined above?
Your method isn't static but you're trying to call it from a static context (main()) Also, your instances in the main() method aren't visible in the loadHtml() method. You could pass them into the method (or declare them as static fields in your class). Finally, you shouldn't swallow Exception (at least printStackTrace()). So I think you were looking for something like,
private static void loadHtml(JEditorPane htmlc, JTextField url, String link) {
try{
htmlc.setPage(link);
url.setText(link);
}catch(Exception e){
System.out.println("ops sorry could not find Virgin Mobile");
e.printStackTrace();
}
}
Also, loadHtml(event.getActionCommand); isn't correct. You'd need parenthesis to call your original method loadHtml(event.getActionCommand());, but with the above changes it would be loadHtml(htmlc, url, event.getActionCommand()); (and to use the htmlc and url references in your inner class you must declare those references as final. For example, final JTextField url = new JTextField(20);).
Alternatively, you could make the components static so they're shared across all instances (and methods - first comment them out in your main method) -
private static final JTextField url = new JTextField(20);
private static final JEditorPane htmlc = new JEditorPane();
private static void loadHtml(String link) {
try{
htmlc.setPage(link);
url.setText(link);
}catch(Exception e){
System.out.println("ops sorry could not find Virgin Mobile");
e.printStackTrace();
}
}
Then you should be able to use loadHtml(event.getActionCommand())

Categories