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 5 years ago.
Improve this question
How to pass actual checkbox state (true/false) from GUI class to another class? I want to run some part of code only if checkbox in GUI is selected. I guess it has to be if statement (highlithed part below) but i cant get it working.
public class csvtoxls {
public static void main() throws IOException {
//here you enter the path to your directory.
//for example: Path workDir = Paths.get("C:\\Users\\Kamil\Desktop\\csvtoxlspython\\Nowy folder (2)")
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
jfc.setDialogTitle("Wybierz folder do konwersji: ");
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jfc.setAcceptAllFileFilterUsed(false);
int returnValue = jfc.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
if (jfc.getSelectedFile().isDirectory()) {
System.out.println("You selected the directory: " + jfc.getSelectedFile());
String z;
//#SuppressWarnings("deprecation")
Path workDir = jfc.getSelectedFile().toPath();
System.out.println(workDir);
//Path workDir = FileSystems.getDefault(jfc.getCurrentDirectory()).jfc.getCurrentDirectory();
//Path workDir = Paths.get(gui.pickPath(jfc));
File dirg = jfc.getSelectedFile();
//String str = dirg.getPath();
// ************* CODE WITH ISSUE *************
if TextAreaLogProgram.checkbox.isSelected() {
try {
Thread.sleep(5000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
String str = dirg.getPath();
delfiles td = new delfiles();
td.deleteFiles(str + "/", ".csv");
System.out.println("SUCCESS!");
msgbox.infoBox("SUCCES!", "CSVtoXLS");
}
GUI class:
public class TextAreaLogProgram extends JFrame {
private JTextArea textArea;
private JButton buttonStart = new JButton("CONVERT");
private JButton buttonClear = new JButton("CLEAR");
private PrintStream standardOut;
public TextAreaLogProgram() {
super("CSVtoXLS");
JCheckBox checkbox = new JCheckBox();
add(checkbox);
checkbox.setText("Delete files");
checkbox.setSelected(true);
Your other class will need a method or constructor with a parameter to be able to accept the value from the other class
See Passing Information to a Method or a Constructor for more details
Other issues:
Your program structure needs to be redone completely. Right now your main method is much too large, meaning that you're doing too much within the static world and not using Java to its best OOPs advantage.
Before even thinking of creating the GUI, first create the non-GUI "model" classes that your program will need. Like all your classes, these should have minimal static fields and methods, and strive to follow object-oriented best practices
You've got a Thread.sleep within your GUI code, something that does not work well with Swing GUI's since this risks putting the entire GUI to sleep, making it non-responsive. If you want Swing delays, use a Swing Timer (google the excellent tutorial on this)
You're trying to check the checkbox as if it were a static field of the TextAreaLogProgram class. It's not a static field and in fact its not even a field of the class.
The fact that you're doing the above suggests that you would benefit greatly from studying introductory tutorials on Object-Oriented programming and Java -- you are putting the cart before the horse by trying to create a GUI before first understanding Java fundamentals. Again, you won't regret the effort expended doing this.
Whatever you do, don't make the JCheckBox a static field and try to access it this way. This will lead to spaghetti code and increased risk for bugs.
Instead, make it a non-static (instance) private field of the TextAreaLogProgram class, and give the class a getter method to allow other objects access to the JCheckgbox's state.
There's so much more that can be mentioned about your code and problem... but this will do for now.
Related
This question already has answers here:
Pass a class variable to another class
(3 answers)
Closed 4 years ago.
I'm stuck on a simple problem that I just can't solve.
I have two classes (Fruits.java with main and FruitDetails.java).
Fruits.java is a small program with tons of stuff, really. It has a ComboBox and I need to transfer its currently selected option to FruitDetails.
The problem is... my understanding of setters and getters seems to be very flawed. I've researched it online for the last 2 hours and this is the closest I could get to something. I'm really tight on time and I can't help but ask you now...
Inside class Fruits.java
public void selectedFruit() {
currentFruit = (String) fruitList.getSelectedItem();
}
public String getSelectedFruit() {
return currentFruit;
}
Inside class FruitDetails.java
public void fruitChoice() {
Fruits fruitChoice = new Fruits();
String chosenFruit = fruitChoice.getSelectedFruit();
System.out.println(chosenFruit);
// Rest of the code
}
Not only this opens another copy of my program(which I really don't want), system prints out "null" for the result.
I really need to get this working and hopefully it'll help fix my understanding of encapsulation a bit. There's a ton of online resources I've found, but using them seems to be too hard for the thick head of mine.
Thanks in advance for any help.
public void fruitChoice() {
Fruits fruitChoice = new Fruits();
String chosenFruit = fruitChoice.getSelectedFruit();
System.out.println(chosenFruit);
// Rest of the code
}
In second line you are creating new object that's why you are getting null when you try to get the value of currentFruit.
it looks like you method selectedFruit() sets currentFruit but your not actually calling selectedFruit()?
Unless your missing some code above that calls selectedFruit() elsewhere?
Try calling selectedFruit() after instantiating your Fruit object.
This is because you have not actually linked your currentFruit to your combo box. You need to do two things - call selectedFruit when you first populate the combo box, then attach a listener that calls selectedFruit everytime the combo box selection changes.
If you are using JComboBox, insert this code after you have created the JComboBox.
combo.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
selectedFruit();
}
})
selectedFruit();
This question already has answers here:
How can I save the state of my program and then load it?
(2 answers)
Closed 6 years ago.
For my program I have two buttons, "Add" and "Save". When I click "Add" a button is added to the JPanel. My question is, how do I save the current state of my program with all the buttons the user added? Do I use serialization?
Here is a snippet of my code:
public class saveButton
{
//JFrame and JPanels have been declared earlier
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String str = JOptionPane.showInputDialog("Name of button");
JButton b = new JButton(str);
frame.add(b);
}
}
ActionListener addButtonClicked = new ClickListener();
b.addActionListener(addButtonClicked);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed(ActionEvent f)
{
//save all of the program
}
}
}
You can only serialize (meaning straight Java serialization) if your object and every non-transient member within the class supports serialization. This is not always possible.
However, you could define your own configuration object that contains the necessary state information and save it whenever (could be just before closing app, could be every time the state changes, it's up to you) and serialization might be a way to do it
It depends on how you save it. You can write the state onto a file and then recover it from there by reading it. The number of buttons and the order etc. You have to decide on the format on how you want to save it too. For example you may want to store in one line
Save,JButton,imageSrc,xpos,ypos
So when you read that line and split on ',' you know that Save is the text, JButton is the class, etc.
Hope this helps
I would write my own file format rather than deal with the overhead of Java's serialization. This has the benefit of being more easily readable in other languages and of slightly better performance. Furthermore, as #MadProgrammer pointed out the Serialization of Swing object is not currently supported and will not be compatible with future releases:
Warning: Serialized objects of this class will not be compatible with
future Swing releases. The current serialization support is
appropriate for short term storage or RMI between applications running
the same version of Swing. As of 1.4, support for long term storage of
all JavaBeans™ has been added to the java.beans package. Please see
XMLEncoder.
(link)
Here is an example:
public void saveState(){
File stateFile = new File("./stateFile");
FileOutputStream fos = new FileOutputStream(stateFile);
DataOutputStream dos = new DataOutputStream(fis);
for(JButton button : jButtons){ //store the buttons in an arraylist when they are created (you could also iterate over the added components and use instanceof)
dos.writeUTF(button.getText());
}
dos.writeUTF("end"); //have some sort of end marker
dos.flush();
dos.close();
fos.flush();
fos.close()
}
public void loadState(){
File stateFile = new File("./stateFile");
FileInputStream fis = new FileInputStream(stateFile);
DataInputStream dis = new DataInputStream(fis);
String name;
while(!(name = dis.readUTF()).equals("end")){
add(new JButton(name));
}
fis.close();
}
Actually, I have a JFrame(the main window) with a JTable in it. And couple of buttons, like Add,Delete,Refresh.
Refresh uses the function(updateTable) that has the following code below and works fine:
try
{
ResultSet R = Home.getStatement().executeQuery("Select * from Schooldata");
int count =0;
while(R.next()) { count++; }
school_data = new String[count][6];
R = Home.getStatement().executeQuery("Select Schoolname,city,ProgramOpted,coordinator_name,Trainers,contactnum from Schooldata");
count =0;
while(R.next())
{
for(int i=0;i<6;i++)
{ school_data[count][i]= R.getString(i+1);
System.out.println(R.getString(i+1));
}
count++;
}
}
catch(SQLException S) {JOptionPane.showMessageDialog(null,S);}
jTable1.setModel(new DefaultTableModel(school_data,new String [] {
"School Name", "City", "Program", "Coordinator", "Trainers", "Contact Number"
}));
When I click on "Add, another JFrame window appears and asks for Details that is further saved to Database and shows a confirmation message and refreshes the table(on a different JFrame i.e the main Window) using above function.
The Issue is, I'm calling the same function but from an another JFrame.Expecting the changes to be reflected in the main JFrame.
Using the method,new Main().updateTable(); in the below code.It's just not working.
try
{
int confirm = Home.getStatement().executeUpdate(Query);
if(confirm == 1)
{
JOptionPane.showMessageDialog(null,"Record Added","Saved",1);
new Main().updateTable();
}
else JOptionPane.showMessageDialog(null,"There is some Error.....","Error",0);
}
catch(SQLException S)
{
JOptionPane.showMessageDialog(null,S,"Error",0);
}
Your problem I believe is here (it's hard to tell without a minimal example program:
int confirm = Home.getStatement().executeUpdate(Query);
if(confirm == 1)
{
JOptionPane.showMessageDialog(null,"Record Added","Saved",1);
new Main().updateTable(); // ****** HERE ******
}
You're creating a completely new Main object, changing its state, and hoping that this will change the state of the visualized Main object, but you're finding out that no, it won't.
Instead you need to pass a reference of the visualized Main object into the code above, and then call methods on it, not on a newly created completely unique object.
Whatever you do, don't try solving this by making fields or methods static. Yes, that might work, but it breaks OOPs and makes your program difficult to test or extend.
As an aside, that second dependent window should not be another JFrame, and in fact likely should be a modal JDialog. For if you use a JDialog, then there would be no need for the dialog code to push information into the calling window. Rather the calling code will know when you're done dealing with the dialog, and so at this point if the dialog's state is good (if you didn't say cancel it with no changes), then the calling code can easily pull information from the dialog code. For a concrete example of what I"m talking about, please look at my answer to a similar question about passing information between two windows here.
Also a similar problem and solution can be found here.
See weather you are disposing the main or not. If not then try creating object of Main frame and try accessing it to refresh table. You can also add import for Main Frame .java file in your refresh dialog file and try refreshing the table. Also check if your table is public static or not so that to access it from another frame. If you create a refresh function for this purpose then it will be best. My code for function goes as -
import package.mainframe;
or
MainFrame mainframe = new MainFrame();
try
{
int confirm = Home.getStatement().executeUpdate(Query);
if(confirm == 1)
{
JOptionPane.showMessageDialog(null,"Record Added","Saved",1);
mainframe.updateTable(); //or mainframe.functioncall();
}
else JOptionPane.showMessageDialog(null,"There is some Error.....","Error",0);
}
catch(SQLException S)
{
JOptionPane.showMessageDialog(null,S,"Error",0);
}
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'm running the main method by clicking a jButton in this class. First tried by using
public static void main(String[]args)
All the java swing components started to show non static variable cannot be referenced from static content errors. So I changed
public static void main(String[]args)
to
public void main(String[]args)
No errors shown for the swing components but expected result are not displaying in the jTextArea. IF i print the expected output in System.out.println, it shows correctly. What am I doing wrong here? This is how i trigger main() to run by clicking on jButton
jButton4.setText("Analyze");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try{
TestTextRazor test = new TestTextRazor();
test.main(new String[0]);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
This is my main()
public void main(String[] args) throws NetworkException, AnalysisException {
File textSRC = new File("MyText.txt");
String myTextCount = null;
BufferedReader myTextBr = null;
String check = "";
try {
String myTextCurrentLine;
myTextBr = new BufferedReader(new FileReader(textSRC));
while ((myTextCurrentLine = myTextBr.readLine()) != null) {
myTextCount = myTextCount + " " + myTextCurrentLine;
}
// Sample request, showcasing a couple of TextRazor features
String API_KEY = "7d5066bec76cb47f4eb4e557c60e9b979f9a748aacbdc5a44ef9375a";
TextRazor client = new TextRazor(API_KEY);
client.addExtractor("words");
client.addExtractor("entities");
client.addExtractor("entailments");
client.addExtractor("senses");
client.addExtractor("entity_companies");
String rules = "entity_companies(CompanyEntity) :- entity_type(CompanyEntity, 'Company').";
client.setRules(rules);
AnalyzedText response = client.analyze(myTextCount);
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
for (Sentence sentence : response.getResponse().getSentences()) {
for (Word word : sentence.getWords()) {
System.out.println("----------------");
System.out.println("Word: " + word.getLemma());
for (Entity entity : word.getEntities()) {
///System.out.println("Matched Entity: " + entity.getEntityId());
}
for (Sense sense: word.getSenses()) {
//System.out.println("Word sense: " + sense.getSynset() + " has score: " + sense.getScore());
}
}
}
// Use a custom rule to match 'Company' type entities
for (Custom custom : response.getResponse().getCustomAnnotations()) {
for (Custom.BoundVariable variable : custom.getContents()) {
if (null != variable.getEntityValue()) {
for (Entity entity : variable.getEntityValue()) {
String CompanyFound = ("Variable: " + variable.getKey() +"\n"+ "Value:" + entity.getEntityId());
System.out.println(CompanyFound);
jTextArea3.append(CompanyFound);
writer.write(CompanyFound);
writer.flush();
writer.close();
}
}
}
}
String ObjButtons[] = {"Yes","No"};
int PromptResult;
PromptResult = JOptionPane.showOptionDialog(null,"Completed Analysis!\nIs there any error in the Analysis?","Homonym Entity Extraction Application",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,null,ObjButtons,ObjButtons[1]);
//JOptionPane.getAlignmentX(Component.BOTTOM_ALIGNMENT);
if(PromptResult==JOptionPane.YES_OPTION)
{
System.out.println("YEs!!!!!");
jTextArea2.setEditable(true);
jTextArea3.setEditable(true);
jButton4.setEnabled(false);
jButton5.setEnabled(true);
}
else{
JOptionPane.showMessageDialog(null, "Completed Analysis!","Alert", 1);
System.out.println("No!!!!!!!!!!");
jTextArea2.setEditable(false);
jTextArea3.setEditable(false);
jButton4.setEnabled(false);
}
}catch (IOException ex) {
}
}
Please guide me.
Basically, the error is saying, you are trying to reference non-static variables from a static context.
Non-static variables (often referred to as instance variables or fields) require an instance of their parent class in order to have some kind referencing context.
Take a look at Understanding Instance and Class Members for more details.
Without much more of an example to go by, I would create a class constructor and move the contents of the main method to it.
I would then fix the main method to be static and create a new instance of the class from the main method...
The reason I would refrain from making Swing components static is it's way to easy to mix up you references and end up referencing something that isn't actually displayed on the screen...
Updated
Two things.
Make sure that the context of your main method is correct, that the UI components that you have created are not static and you are referencing them correctly.
Don't call the TestTextRazor class directly. This is just an example of how the API works. Take the time to understand it and incorporate into your own class(es) as required
Firs of all, what you need to understand is that a static method cannot access class fields or other methods that are non-static. So look at your code. The main has to be static as that is its natural signature, which must remain in tact as is. So all your class fields that you are trying to access in the main method, need to be static. Is this good practice? Absolutely not. You can browse through the Swing tutorial to pick up on good practices. I'm sure if you run through 20 examples, you'll pick up on a lot of good coding practices for Swing. Good Luck!
"I'm running the main method by clicking a jButton in this class"
One thing I noticed that you are doing complete wrong is trying to call the main method from inside your actionPerformed. The main method should never be called. The JVM using that method as an entry point for your program.
Another thing you have to understand is that a Swing program is event-driven. One button, should not run a complete program, unless it is a very small program.
I would consider creating methods for different tasks like
public String getSomethingFromFile(String filename) throws IOExceptions {
}
where you can call that method from an actionPerformed or something to append data to a text area.
Learn to use class members and initialize them in your constructor or some initialization method.
If you want everything that's going on the main method to be performed on a button click, put all that code in the actionPerformed , not in the main. A typical form of what goes inside the main is just something like this, where you just need to initialize your class to get the program running
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
JFrame frame = new JFrame();
frame.add(new MyGUIPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
where new MyGUIPanel() is an instance of your Main class
Another option is to create a method to perform all the tasks that are in the main like
public void performTextRazorTask() throws NetworkException, AnalysisException {
...
}
and just call that method from the actionPerformed
Again, I stress that you have a look at the tutorials I linked for better practices, as this site isn't really a tutorial site, I don't want to get into a tutorial type answer.
First of all you can not make main method as non static.
As per this line non static variable cannot be referenced from static content errors. make those variables as static
This is my first attempt at a decent GUI for a Java app and I needed to use JLists with custom ListModels in order to represent certain structures.
//The 2 below structures implement the ListModel interface, using an internal
//ArrayList, in order to be used as
//a model for 2 different JLists in my GUI.
private PropertyList propertiesList = new PropertyList();
private SelectedProperties selProperties = new SelectedProperties();
//and these are the two JLists they are the models for
private javax.swing.JList Properties_JList;
private javax.swing.JList SelectedProperties_JList;
Here I populate my first JList via a stream:
private void OpenFile_MenuItemActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(null);
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
this.Properties_JList.setModel(propertiesList);
this.propertiesList.AddFromFile(file);
} else {
//...
}
}
which happens to be working perfectly fine. I import a few entries by reading the file and they are all displayed as expected in a .toString() representation.
The problem is the second JList:
private void AddToSelected_JButtonActionPerformed(java.awt.event.ActionEvent evt) {
Property p = (Property) this.Properties_JList.getSelectedValue();
this.SelectedProperties_JList.setModel(selProperties);
this.selProperties.InsertProperty(p);
this.SelectedProperties_JList.revalidate();
}
Which appears to be displaying only the very first item I attempt to add to it through the above button event, and I have no idea why. I considered moving both .setModel(...) calls right after the form's initComponents() call but if I do that none of the lists gets populated, at all.
Logging messages made it clear that the internal structures are getting populated, but even though they are both respective ListModels for my JLists, one of them isn't working as expected.
A sufficient portion of the code is generated by Netbeans and I have spent hours looking up the API but still have trouble finding out what I'm doing wrong. Any ideas?