implementing jlabel by codes in an automated jFrame in netbeans 6.9 - netbeans

Hi
i'm new with java swing,i try a lot and do a lot of search but in vain.i want to display a jlabel(not by drag n drop but with codes) on an automated jFrame that i have already.well my code for my JLabel is as follows:
private JLabel la=new JLabel("Display label");
codes that i got during my search to dispaly in a jpanel was like follows:
jPanel1.add(jLabel1);
but it does not work.My jPanel1 was built by drag n drop with the name Jpanel1.
i even try this piece of code:
this.add(jLabel1)--
this.getContentPane().add(jLabel1)
but still not working.
Please help me,it must be a simple line of code or i'm missing something somewhere ,please..thank you

This is a simple piece of code obtained from link text
public class HelloWorldFrame extends JFrame {
public static void main(String args[]) {
new HelloWorldFrame();
}
HelloWorldFrame() {
JLabel jlbHelloWorld = new JLabel("Hello World");
add(jlbHelloWorld);
this.setSize(100, 100);
// pack();
setVisible(true);
}
}
What you need to do is to re-set the setVisible property of the parent component to true

Related

Saving string variables in a custom EditorWindow while formatted like a TextArea

Basically, I want to figure out how I can:
Save string (or any) variables in a custom editor window (inheriting
from EditorWindow) when they are changed in that window.
Display strings in a format like a TextArea while still allowing
saving changes as mentioned above.
Display strings from a string array by index, rather than individually defined strings (I've had trouble with this before)
If you know how to do the above in a custom inspector too
(inheriting from Editor, not EditorWindow), that'd be great too.
I've run into this issue a few times with different classes inheriting from Editor, and previously solved by using a PropertyField rather than a TextArea/TextField, but that gets rid of the TextArea-style formatting that I want.
Also, classes inheriting from EditorWindow don't seem to allow it in the same way (t = (script type)target; doesn't work, and PropertyField needs it)..?
I'm pretty new to custom inspectors and this stuff, so code examples would be super helpful if possible.
Thanks!
Before starting a general note because you mentioned it in your question:
Whenever possible I strongly recommend to avoid using target at all! In particular do not set any fields directly. this makes things like marking your scene direty and thus saving changes and also Undo/Redo functionality pretty complicated as you will have to implement it by yourself!
Rather always go through SerializedProperty combined with SerializedObject.Update and SerializedObject.ApplyModifiedProperties (examples will be below). This handles all this stuff like marking dirty and thus saving the scene changes and Undo/Redo automatically for you!
Then to the TextArea.
Lets say you have a class like
public class Example : MonoBehaviour
{
[SerializeField] private string _exampleString;
public string AnotherExampleString;
}
Basically there are three main options. I will do the Editor (custom Inspector) script first since there you are a bit more flexible.
The EditorWindow will be below.
Editor Attribute [TextArea]
Actually you wouldn't even need an Editor script at all! Simply tag the according field(s) as [TextArea] like this:
public class Example : MonoBehaviour
{
[SerializeField] [TextArea] private string _exampleString;
// You can also directly configure the min and max line count here as well
// By default it is 3 lines
[TextAre(3,7)] public string AnotherExampleString;
}
This already looks like this
EditorGUILayout.PropertyField
Then if you still need the Editor script the good thing about a EditorGUILayout.PropertyField is it automatically uses the correct drawer for the according type ... and it also applies all editor attributes! Isn't this great?
So simply having and Editor like
[CustomEditor(typeof(Example))]
public class ExampleEditor : Editor
{
private SerializedProperty _exampleString;
private SerializedProperty AnotherExampleString;
private void OnEnable()
{
// Link in the serialized properties to their according fields
_exampleString = serializedObject.FindProperty("_exampleString");
AnotherExampleString = serializedObject.FindProperty("AnotherExampleString");
}
public override void OnInspectorGUI()
{
DrawScriptField();
// load the real target values into the serialized properties
serializedObject.Update();
EditorGUILayout.PropertyField(_exampleString);
EditorGUILayout.PropertyField(AnotherExampleString);
// write back the changed properties into the real target
serializedObject.ApplyModifiedProperties();
}
// Little bonus from my side so you have the script field on top
private void DrawScriptField()
{
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour((Example)target), typeof(Example), false);
EditorGUILayout.Space();
EditorGUI.EndDisabledGroup();
}
}
The result looks basically exactly the same:
EditorGUILayout.TextField
Using a EditorGUILayout.TextArea you can display any string as a multi-line text area. This also applies to an EditorWindow.
Lets say again we didn't tag our string fields
public class Example : MonoBehaviour
{
[SerializeField] private string _exampleString;
public string AnotherExampleString;
}
But we can make them appear just as before using this Editor script:
[CustomEditor(typeof(Example))]
public class ExampleEditor : Editor
{
private SerializedProperty _exampleString;
private SerializedProperty AnotherExampleString;
private Vector2 scroll1;
private Vector2 scroll2;
private void OnEnable()
{
// Link in the serialized properties to their according fields
_exampleString = serializedObject.FindProperty("_exampleString");
AnotherExampleString = serializedObject.FindProperty("AnotherExampleString");
}
public override void OnInspectorGUI()
{
DrawScriptField();
// load the real target values into the serialized properties
serializedObject.Update();
EditorGUILayout.PrefixLabel(_exampleString.displayName);
scroll1 = EditorGUILayout.BeginScrollView(scroll1,GUILayout.MaxHeight(3 * EditorGUIUtility.singleLineHeight));
_exampleString.stringValue = EditorGUILayout.TextArea(_exampleString.stringValue, EditorStyles.textArea);
EditorGUILayout.EndScrollView();
EditorGUILayout.PrefixLabel(AnotherExampleString.displayName);
scroll2 = EditorGUILayout.BeginScrollView(scroll2, GUILayout.MaxHeight(7 * EditorGUIUtility.singleLineHeight));
AnotherExampleString.stringValue = EditorGUILayout.TextArea(AnotherExampleString.stringValue);
EditorGUILayout.EndScrollView();
// write back the changed properties into the real target
serializedObject.ApplyModifiedProperties();
}
// Little bonus from my side so you have the script field on top
private void DrawScriptField()
{
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour((Example)target), typeof(Example), false);
EditorGUILayout.Space();
EditorGUI.EndDisabledGroup();
}
}
Though you can see we already had to fake it a bit using the additional EditorGUILayout.BeginScrollView
This same thing you can also do in an EditorWindow. Most of the times it makes not much sense to go through SerializedProperty for EditorWindow
public class ExampleWindow : EditorWindow
{
private string exampleString;
private Vector2 scroll;
[MenuItem("Example/Show ExampleWindow")]
private static void Initialize()
{
var window = GetWindow<ExampleWindow>();
window.Show();
}
private void OnGUI()
{
EditorGUILayout.PrefixLabel("Example String");
scroll = EditorGUILayout.BeginScrollView(scroll,GUILayout.MaxHeight(3 * EditorGUIUtility.singleLineHeight));
exampleString = EditorGUILayout.TextArea(exampleString, EditorStyles.textArea);
EditorGUILayout.EndScrollView();
}
}
which results in

How can insert a jlabel inside a jdesktop pane in netbeans. When i tried to drag and drop it didn't work? The desktop pane got displaced

I also tried to enclose the label inside a dekstop pane. But a message flashed that cannot enclose components in a non-empty container. Any help shall be appreciated
Using Netbeans 11.0 I was able to drag a JLabel into a JDesktopPane and I did not see the error you reported. However I believe that JDesktopPane was designed just to be a container for JInternalFrames rather than having other components embedded directly. This was for MDI applications that aren't seen so much these days.
Have a look at the relevant Swing Tutorial for background info.
I have also put a minimal example here which you can paste into an empty class in Netbeans
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JDesktopPane desktop_pane = new JDesktopPane();
frame.getContentPane().add(desktop_pane);
for (int i = 1; i <= 5; ++i) {
JInternalFrame internal = new JInternalFrame(String.format("Window %d", i), true, true, true, true);
internal.setSize(150, 80);
internal.setLocation(i * 50, i * 50);
internal.setVisible(true);
desktop_pane.add(internal);
}
desktop_pane.setPreferredSize(new Dimension(800, 600));
frame.pack();
SwingUtilities.invokeLater(() -> {
frame.setVisible(true);
});
}
It will create a desktop with five resizeable windows in it.

Switching scenes the FXML way (SceneBuilder)

I have two scenes, scene 1 has a Label on it that simply reads "This is scene 1", it also has a button on it with the text "Press me to go to scene 2". scene 2 is similar to scene 1 but the Label and text on scene 2 say the opposite.
The problem is very simple, or at least should be. I am able to do this the javaFX way but cannot seem to do it the FXML way.
I have a main class -
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class ManinApp extends Application
{
Stage primaryStage;
private AnchorPane rootLayout;
public static void main(String [] args)
{
launch(args);
}
public void start(Stage primaryStage)
{
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Two Scenes");
initRootLayout();
//showSecondScene();
}
public void initRootLayout()
{
try
{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(ManinApp.class.getResource("Scene1.fxml"));
rootLayout = (AnchorPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
/**
public void showSecondScene()
{
try
{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(ManinApp.class.getResource("Scene2.fxml"));
AnchorPane secondScene = (AnchorPane)loader.load();
rootLayout.getChildren().add(secondScene);
}
catch(IOException e)
{
e.printStackTrace();
}
}
*/
public Stage getPrimaryStage()
{
return primaryStage;
}
}
the showSecondScene() has been commented out for now. My understanding is that you also need a Controller class to wire up the code to SceneBuilder?
the solution the FX way was
btnscene1.setOnAction(e ->
{
if(e.getSource() == btnscene1)
thestage.setScene(scene2);
else
thestage.setScene(scene1);
});
btnscene2.setOnAction(e ->
{
if(e.getSource()==btnscene2)
thestage.setScene(scene1);
else
thestage.setScene(scene2);
});
apologies for the formatting!
how am I able to do this using a controller class from which i am able to use the primary stage and two scene declared in my main class?
i hope it makes sense
I think your are doing quite well. FXML (and SceneBuilder) are used correctly here.
I would suggest few things:
Use a root container (e.g. StackPane) to host either scene1 or scene2
(better names would be layout1 / layout2). You don't need to use
different Scene here.
Load both fxml files at init time (or lazy loading if needed)
switch from one to the other by removing the content of the root container, and adding the other one.
Now, if the layouts are big, with a lot of css involved, and you need to switch very often from layout1 to layout2, you may want to add both layout in the root container. Then, use:
setVisible()
setManaged()
... on the root of the layout you want to hide / show.
Doing this, you avoid the layout and css steps that is done as soon as you add a node in the scene graph.
While I technically understand, what you want to achieve, I'm still lost about the reason behind it.
If you just want to switch the "main" content of the window, use a StackPane as the root, add multiple Layouts to that stack, and solve your problem by switching the one you want to work on #toFront().
Normally the Layouts on the stack are transparent (except for the controls like buttons and so on, of course), so you would either need to set a background of the stacked Layouts OR (which I would prefer) toggle the visibility of the one in the back (or set opaqueness to 0, or something like that).

StartCoroutine get error NullReferenceException

I have two cs files, Main.cs and Menu.cs. On OnGUI event which is in Main.cs file I call method from Menu.cs.
private void OnGUI()
{
Menu menu=new Menu();
menu.Create_Menu();
}
And in Menu.cs.
public void Create_Menu ()
{
StartCoroutine(LoadCar());
}
private IEnumerator LoadCar()
{
//Load Object
Download download;
download=new Download();
GameObject go = null;
yield return StartCoroutine(LoadAsset("http://aleko-pc/3dobjects?key=1017&objecttype=1","car13",(x)=>{go = x;}));
}
I get error NullReferenceException
UnityEngine.MonoBehaviour.StartCoroutine (IEnumerator routine)
If I copy private IEnumerator LoadCar() method in Main.cs class, and call from OnGUI it works.
Maybe I do not understant working area of Coroutines, Can any body help me?
First of all the OnGUI method is called every frame and I don't think you want to download the assets every frame.
Second, you need to make sure Menu is derived from MonoBehviour and added to the view hierarchy.
A better approach would be to add Menu as a component to a GameObject (maybe the same that has the Main script attached) and call Create_Menu on the Start method of Menu.

How to restrict the minimum size of the window for Eclipse e4

I am making an application based on Eclipse e4 framework. I was wondering how the minimal size of the application window can be controlled. There seems no properties can be defined in e4xmi file for this purpose.
Does anyone know how to do it?
I found a thread in Eclipse Community Forum (http://www.eclipse.org/forums/index.php/t/244875/) saying it can be achieved by creating my own renderer. How can I do that exactly?
Thank you very much :)
Assuming you are using the built-in SWT Renderers, you can also listen for the creation of your E4 MWindow elements and gain access to the underlying SWT Shell. In this example the listener is registered in an AddOn, which you can add to your e4xmi.
import javax.annotation.PostConstruct;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.e4.ui.model.application.ui.basic.MWindow;
import org.eclipse.e4.ui.workbench.UIEvents;
import org.eclipse.swt.widgets.Shell;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
public class MinSizeAddon {
#PostConstruct
public void init(final IEventBroker eventBroker) {
EventHandler handler = new EventHandler() {
#Override
public void handleEvent(Event event) {
if (!UIEvents.isSET(event))
return;
Object objElement = event.getProperty(UIEvents.EventTags.ELEMENT);
if (!(objElement instanceof MWindow))
return;
MWindow windowModel = (MWindow)objElement;
Shell theShell = (Shell)windowModel.getWidget();
if (theShell == null)
return;
theShell.setMinimumSize(400, 300);
}
};
eventBroker.subscribe(UIEvents.UIElement.TOPIC_WIDGET, handler);
}
}
Note, that this will be executed for any MWindow in your application, and there can be more of them (i.e. when an MPart is detached from the MPartStack into a seperate window). If you want to limit the execution to specific MWindows, I recommend to add a tag to the window in the e4xmi and check for this tag before setting the minimum size.
If anyone is still looking to do this in an e4 application and doesn't want to roll their own renderer, you can simply do the following in the post-construct of your part class:
#PostConstruct
public void postConstruct(Composite parent) {
parent.getShell().setMinimumSize(300, 300);
//...
}
The parent Composite passed in by the framework gives you access to the Shell, which lets you set the minimum size. This stops the application from being resized to less than the specified minimum size (in pixels).