NetBeans Swing TextArea is not static, causes trouble - java

I have created a JFrame with a textArea called 'outputTextArea' and I want to print the results from a database query in the textArea. However, the variable outputTextarea is not static and therefore I can't call the method setText() in the main method to print the db resultset in the textArea.
I would like to know how I can make this variable (private javax.swing.JTextArea outputTextArea;) static, because NetBeans won't let me edit this variable because it was generated by NetBeans when I dragged and dropped the textArea.

I had the same problem.
In Netbeans IDE 8.0.2:
1) In the design tab
2) Click on the textarea
3) go to properties -> code
4) Variable Modifiers -> add static.
It worked for me.

Just add an accessor method to your class that adjusts the field. For instance:
public void setTextAreaText(String newText) {
outputTextArea.setText(newText);
}
Then anyone with a reference to your class can adjust the text in the text area. Just be sure to call that method from the Event Dispatch Thread. This is usually achieved with SwingUtilities.invokeLater
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myClassReference.setTextAreaText("Hello, World");
}
});
See the documentation on Event Dispatch Thread if this sort of thing is new to you. It's important to get threading correct when using Swing.

If you just want to edit codes. Open code with another editor just like notepad or something. And if you remove GEN-BEGIN:initComponents just before the auto generated code you can edit code through netbeans also.

Related

Can't change/modify button background from another method - JAVA

I have a problem about modify button background. I am using netbeans gui builder for build form. I am trying change button background when the second frame is open and turn it back when second frame close.
public void update(boolean x){
if(x==true){
circleButton.setOpaque(true);
circleButton.setBackground(new java.awt.Color(0, 0, 0));
System.out.println("testoutput");
}
}
this is my update method from first class.
I added window listener to second frame.
private void formWindowOpened(java.awt.event.WindowEvent evt) {
isitopen = true;
//this is first class which includes button
homework hwork = new homework();
hwork.update(isitopen);
System.out.println("testoutput2");
}
I got 2 testoutput but color of the button didn't change.
What can i do to fix this issue ?
You're creating a new homework object in your formWindowOpened(...) method, one completely unrelated to the homework object that is displayed, and changing the state of the new object will have no effect on the displayed one.
A simple and WRONG solution is to use static fields or methods.
Instead one simple solution is to give the calss with your formWindowOpened(...) method a valid reference to the displayed homework object, something that can be done with a constructor parameter or a setHomework(...) method.
A much better and even simpler solution:
Make the 2nd window a modal JDialog, not a JFrame
This way homework will know when the window is open and can set its own button colors. When the 2nd window opens, program flow in the calling class is put on hold, and only resumes when the 2nd window closes -- just like using a JOptionPane.
For more on this, please see The Use of Multiple JFrames, Good/Bad Practice?
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.

How to execute some action after the JFrame are displayed

I have this GUI application, and I want to execute a custom action inmediatelly when the user open the application, but after the GUI are shown.
So, I put the call to the action into the public Main() of the JFrame like this:
public Main() {
initComponents();
ExecuteAfter();
}
Where ExecuteAfter() is the method that contain the acction, or actions to execute.
This works fine, but not in the way I want. This way, the action executes allways before the JFrame are displayed, that is before the aplication windows appear in the screen. What I want is that execute the action only after the JFrame are displayed, that is after the aplication windows appear in the screen.
I tried put the call into the public static void main(String args[]) because there's where the JFrame is created and displayed. But doesn't work because the method isn't static, and I can't put static that method because it use some components of the JFrame that are already initialized non-static by the IDE.
So, the question is: Where I need to put the call for the action can be executed after the JFrame are displayed on the screen? Or there's other way of doing that?
Thanks in advance!
I used a WindowListener and solved the problem.
Instead of put the call in the constructor public Main() or in the main public static void main(String args[]) which cannot be done, I configured a WindowsListener for do the call. Like that:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
ExecuteAfter();
}
And works perfectly in the way I want.
Thanks #MadProgrammer for the tip.
If i understand you question, I use a similar case for my project. I was needed to start timer when JFrame show, so this is how i do that.
So i use 2 methods and 1 constructor. First method (exp. Name: prepare GUI), here you can add all thinks what you need to create JFrame, JPanel....and that method I call in constructor. In second method (exp. Name: start GUI) you will add all components to JPanel/s, JPanel/s to JFrame, and set JFrame visible = (true) and then add your method ExecuteAfter(). That second method(prepare GUI) you need to call in main method. I hope that's will help you.

Java JTabbedPane can't add multiple tabs?

I'm re doing a specific application, just a basic text editor and I remember I had tabs and a JMenu so if you went File --> New it would add or 'Open' another tab on the JTabbedPane. But this time it's not doing it for me, could someone help? Here is how im doing it:
newFile.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
tabs.addTab("new file", text);
}
}
);
So when it's clicked it should add another tab but it's not for some reason...
If it matters there is a default tab open at the beginning and when you click new it wipes out the old one.
Thanks for any help! (Please ask if you need anymore explanation)
Here I uploaded my code here since the editor here kept saying I the way I was putting it in wasnt formatted correctly:
http://nardcake.com/java
There is 2 files there, one initializes it and the other is everything else
thanks!
try:
tabs.revalidate();
tabs.repaint();
I have removed these two lines (those two are anyhow called in the end by addTab() method), and rewritten your init.java like this:
public static void main(String[] args) {
System.out.println(SwingUtilities.isEventDispatchThread()); // 1
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
System.out.println(SwingUtilities.isEventDispatchThread()); //2
EBLFWE window = new EBLFWE();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setExtendedState( window.getExtendedState()|JFrame.MAXIMIZED_BOTH );
window.setSize(1024, 728);
window.setVisible(true);
}
});
It works now. To quote myself:
Every usage of Swing components must be done thorugh the Event Dispatch Thread (abbreviated EDT) or you will probably get unwanted visual effects. See here for explanation.
EDIT:
All the GUI related code must be executed on the EDT. You can test if some part of your code is run by EDT like this:
System.out.println(SwingUtilities.isEventDispatchThread());
If it prints true you are safe to do a GUI update (e.g. call methods on Swing components instances) - like in 1 or anywhere in EBLFWE class. However 2 will print false - it is because the thread that runs your program is not EDT.
When calling SwingUtilities.invokeLater() you are actually placing that code to be executed (at some appropriate time the EDT sees fit) in the Event dispatch thread.
EDT does the actual painting, and a lot of other tasks, so when you call GUI update code from another thread you can mess up the order and get unwanted visual apperance.

Java: Calling static method but nothing happens?

I have a class called GUI which basically creates a latout using Swing. In that class i have a method called "log" which is supposed to add a new line to a textarea in the layout.
The problem is that whenever i call the function from outside of the GUI class, nothing happens. If i call the method from within the class it adds a line to the textarea as it's supposed to do.
I have set the method and all the variables it calls to public static, and i don't get any errors. It just doesn't do anything when i call the method from the outside.
Any ideas?
Edit:
Here's the method within the GUI class:
public static void log(String inputString) {
logConsole.append(inputString + "\r\n");
}
At the bottom of the class swing declared the textarea, and i just modified it to be public static instead of private.
public static javax.swing.JTextArea logConsole;
Can't post more code, hope this is at least a little bit helpful? :/
It's most likely a concurrency issue with Swing. Since Swing is single-threaded, Swing components need to be modified in the Event Dispatch Thread (i.e. EDT). For more information, see Concurrency in Swing.
EDIT -
If this is indeed a concurrency issue, then one quick workaround would be to use SwingUtilities. In particular, isEventDispatchThread() and invokeLater(...). For instance,
if(!SwingUtilities.isEventDispatchThread()){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
GUI.log("foo"); // modify textarea in EDT
}
});
}
else{
// your problem lies elsewhere
}

jTabbedPane opens different tab on loading

First of all I'm using netbeans as my IDE and I don't know if this is causing it. When I run my program (even if I have build it and run the .jar) I think it selects the tab that was previously selected (before quiting). So if for example I close the app with the third tab selected, it starts up with that selected again. Is there a known solution for this? The selectedIndex property on the jTabbedPane is set to 0. Shouldn't this property be the default onLoad value?
Thx in advance, Jimmy
PS. BTW for some reason it didn't submit my question in Opera (?)
tabbedPaneName.setSelectedIndex(0);
just put that line in the place where the tabbed pane would be loaded
if a button actuion will load the tabbed pane then put the line there
but change tabbedPaneName to YOUR tabbed pane name.
Same problem here with Netbeans 6.8 and JTabbedPane. Neither setSelectedIndex() nor setSelectedComponent() makes a difference. The getSelectedIndex() returns the value previously set, but the pane is not selected correctly.
The reason for this is that the SingleFrameApplication saves it's state and restores the saved state on the next restart. This is done in the code generated by the GUI builder.
You could see that startup() and configureWindow() methods of the SingleFrameApplication are overridden.
Workarounds:
You could override the shutdown() method as well, then modifications to the configuration will not be saved. Note that the original will still be restored, so ensure that the required configuration is saved.
Modifying the startup() method also helps:
MyView myView = new MyView(this);
myView.getFrame().setVisible(true);
myView.getFrame().pack();
The only way it can be set to an index other than zero is if the Java code contains:
tabbedPane.setSelectedIndex(...);
So search the source code for that line and fix it.
Besides using JTabbedPane.setSelectedIndex(), it's also possible to select a tab by calling JTabbedPane.setSelectedComponent(). Have you searched the code for setSelectedComponent() as well?
I had the same problem and found an easy workaround.
In netbean's GUI-builder I set my tabbedpane to not enabled. Later in my program I checked if it was not enabled and in that case called MyTabbedPane.setEnabled(true); and MyTabbedPane.setSelectedIndex(0);
Same problem. Had to go back to NetBeans 7.0.1 to update a JSR 296 application and Java 7 runs it differently than previous versions did so the last tab created was always the one that had focus. Couldn't get anything to change that in the constructor, but finally found just wrapping the same call (setSelectedIndex()) in a call to invokeLater() solves it.
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
tabMain.setSelectedIndex(0);
}
}
);

Categories