I'm running this in netbeans and it's not displaying anything. Does anyone know why netbeans isn't displaying the User Interface? Is it because I'm using an empty java file? My Code is below. I am new to netbeans and java so any help would be appreciated.
import java.awt.*;
import javax.swing.*;
class UserInterface extends javax.swing.JFrame {
public UserInterface() {
setTitle("My First UI");
setLayout(null);
setBounds(10,10,400,600);
Container con = getContentPane();
JLabel lblCustomerName = new JLabel("Customer Name");
JTextField txtCustomerName = new JTextField();
JButton btnOkay = new JButton("Okay");
lblCustomerName.setBounds(20,20,100,20);
txtCustomerName.setBounds(125,20,100,20);
btnOkay.setBounds(20,300,80,60);
con.add(lblCustomerName);
con.add(txtCustomerName);
con.add(btnOkay);
con.setVisible(true);
}
}
class Tester {
public static void main(String[] args) {
new UserInterface();
}
}
Your java code cannot show your frame.
Please set in your Tester.class:
class Tester {
public static void main(String[] args) {
UserInterface ui = new UserInterface();
ui.setVisible(true);
}
}
And you could remove con.setVisible(true); from your UserInterface.class.
Related
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUITest {
private JPasswordField passwordBox;
private JButton enterButton = new JButton ("Enter");
private JLabel textBox = new JLabel("Enter Password Here:");;
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
public void GUITest() {
PanelSetup();
FrameSetup();
}
public void PanelSetup(){
panel.setBorder(BorderFactory.createEmptyBorder(150, 150, 250, 250));
panel.setLayout(new GridLayout(0,1));
}
public void FrameSetup(){
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setTitle("GUI TEST");
frame.pack();
frame.setVisible (true);
}
public static void main (String[] args) {
new GUI();
}
}
Unfortunately, the problem is creating the new GUI and I cannot run the code to see if the rest of it works and/or adding more stuff to it. If you can help that would be much appreciated
Change "new GUI();" to "new GUITest();" as you are creating a new instance of the current class.
public static void main (String[] args) {
new GUI();
}
to
public static void main (String[] args) {
new GUITest();
}
Also, remove the void tag from your constructor as it turns it into a method.
public void GUITest() {
PanelSetup();
FrameSetup();
}
to
public GUITest() {
PanelSetup();
FrameSetup();
}
It seems like you're new to java, welcome! I'd take a look at w3schools excellent java docs if you want to get better at syntax. w3schools java
I am creating a javaFx application that runs in Mac OSX El Capitan. When I create a bundle from my jar file to .app file, the application window dimension changes.
I want window dimension to be the same before and after bundling. Any help is appreciated.
As I known JavaFX doesn't save/restore window position/dimension automatically.
So, you should restore window position/dimension before show window and save then before window hide. For example I am using such helper:
import javafx.stage.Stage;
import java.util.prefs.Preferences;
public class StagePositionManager {
public static final String IS_FIRST_RUN_KEY = "isFirstRun";
public static final String X_KEY = "x";
public static final String Y_KEY = "y";
public static final String WIDTH_KEY = "width";
public static final String HEIGHT_KEY = "height";
private final Stage stage;
private final Class<?> windowClass;
public StagePositionManager(Stage stage, Class<?> windowClass) {
this.stage = stage;
this.windowClass = windowClass;
restoreStagePosition();
stage.setOnHidden(event -> saveStagePosition());
}
private void saveStagePosition() {
Preferences preferences = Preferences.userNodeForPackage(windowClass);
preferences.putBoolean(IS_FIRST_RUN_KEY, false);
preferences.putDouble(X_KEY, stage.getX());
preferences.putDouble(Y_KEY, stage.getY());
preferences.putDouble(WIDTH_KEY, stage.getWidth());
preferences.putDouble(HEIGHT_KEY, stage.getHeight());
}
private void restoreStagePosition() {
Preferences preferences = Preferences.userNodeForPackage(windowClass);
if (!preferences.getBoolean(IS_FIRST_RUN_KEY, true)) {
stage.setX(preferences.getDouble(X_KEY, 0));
stage.setY(preferences.getDouble(Y_KEY, 0));
stage.setWidth(preferences.getDouble(WIDTH_KEY, 1024));
stage.setHeight(preferences.getDouble(HEIGHT_KEY, 768));
}
}
}
and call it after application start:
public class MyApplication extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
...
new StagePositionManager(primaryStage, Main.class);
...
when I use this code the result is empty page:
public class Vaadin6biuApplication extends Application {
#Override
public void init() {
xx a = new xx();
Window w = new Window("aness conf");
w.addComponent(a);
setMainWindow(w);
}
}
public class xx extends CustomComponent {
#AutoGenerated
private AbsoluteLayout mainLayout;
#AutoGenerated
private Button button_1;
public xx() {
buildMainLayout();
setCompositionRoot(mainLayout);
}
#AutoGenerated
private AbsoluteLayout buildMainLayout() {
mainLayout = new AbsoluteLayout();
mainLayout.setImmediate(false);
button_1 = new Button();
mainLayout.addComponent(button_1, "top:100.0px;left:100.0px;");
return mainLayout;
}
}
how to add custom component to application?
thank you for your answers
Have you read the wiki tutorial for vaadin6 + spring? With spring > 2.5 it's fairly simple:
#Configurable(preConstruction = true)
public class SpringHelloWorld extends com.vaadin.Application {
#Autowired
private MyBeanInterface bean;
public void init() {
final Window main = new Window("Hello window");
setMainWindow(main);
main.addComponent(new Label( bean.myMethod() ));
}
}
I am trying to get an image to display inside my JFrame and having no success. I have followed the Oracle tutorial exactly and I get a NullPointerException:
Exception in thread "main" java.lang.NullPointerException
at net.ultibyte.TheDo.CreateLoginScreen.DisplayImage(CreateLoginScreen.java:35)
at net.ultibyte.TheDo.CreateLoginScreen.main(CreateLoginScreen.java:41)
Below is my code.
public class CreateLoginScreen extends JFrame {
CreateLoginScreen() {
setTitle("TheDo");
setSize(1280, 720);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static Image loadImage() {
Image i = null;
try {
i = ImageIO.read(new File("src/resources/LoginScreen.png"));
} catch (IOException e) {
}
return i;
}
public static void DisplayImage(Image i) {
Graphics g = i.getGraphics();
g.drawImage(i, 0, 0, null);
}
public static void main(String[] args) {
CreateLoginScreen a = new CreateLoginScreen();
DisplayImage(loadImage());
}
}
And the image is named "LoginScreen.png", and is located in a package called "resources" which is in the src folder.
I have no idea what's wrong and would very much appreciate any help :).
Update: Corrected file path, pointed out by peeskillet. This fixed the NullPointerException. Still won't display image though.
"located in a package called "resources" which is in the src folder."
You need to use this file path. "src/resources/LoginScreen.png"
Your IDE will first look in the main project folder. since src is direct child of the project root, you need to add that to the path
EDIT
"The window loads up but no image is displayed. Any idea on this? "
Yes, you need to override a paint method in order to draw the image on to the component. I wouldn't use JFrame though. I would use a JPanel and override the paintComponent method.
Try this out
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
class JPanelTemplate extends JPanel {
private static final int SCREEN_WIDTH = 400;
BufferedImage img;
public JPanelTemplate() {
try {
img = ImageIO.read(new File("src/resources/LoginScreen.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(SCREEN_WIDTH, SCREEN_WIDTH);
}
private static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new JPanelTemplate());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I've converted my AsyncTask to an AsyncTaskLoader (mostly to deal with configuration changes). I have a TextView I am using as a progress status and was using onProgressUpdate in the AsyncTask to update it. It doesn't look like AsyncTaskLoader has an equivalent, so during loadInBackground (in the AsyncTaskLoader) I'm using this:
getActivity().runOnUiThread(new Runnable() {
public void run() {
((TextView)getActivity().findViewById(R.id.status)).setText("Updating...");
}
});
I am using this in a Fragment, which is why I'm using getActivity(). This work pretty well, except when a configuration change happens, like changing the screen orientation. My AsyncTaskLoader keeps running (which is why I'm using an AsyncTaskLoader), but the runOnUiThread seems to get skipped.
Not sure why it's being skipped or if this is the best way to update the UI from an AsyncTaskLoader.
UPDATE:
I ended up reverting back to an AsyncTask as it seems better suited for UI updates. Wish they could merge what works with an AsyncTask with an AsyncTaskLoader.
It's actually possible. You essentially need to subclass the AsyncTaskloader and implement a publishMessage() method, which will use a Handler to deliver the progress message to any class that implements the ProgressListener (or whatever you want to call it) interface.
Download this for an example: http://www.2shared.com/file/VW68yhZ1/SampleTaskProgressDialogFragme.html (message me if it goes offline) - this was based of http://habrahabr.ru/post/131560/
Emm... you shouldn't be doing this.
because how an anonymous class access parent class Method or Field is by storing an invisible reference to the parent class.
for example you have a Activity:
public class MyActivity
extends Activity
{
public void someFunction() { /* do some work over here */ }
public void someOtherFunction() {
Runnable r = new Runnable() {
#Override
public void run() {
while (true)
someFunction();
}
};
new Thread(r).start(); // use it, for example here just make a thread to run it.
}
}
the compiler will actually generate something like this:
private static class AnonymousRunnable {
private MyActivity parent;
public AnonymousRunnable(MyActivity parent) {
this.parent = parent;
}
#Override
public void run() {
while (true)
parent.someFunction();
}
}
So, when your parent Activity destroys (due to configuration change, for example), and your anonymous class still exists, the whole activity cannot be gc-ed. (because someone still hold a reference.)
THAT BECOMES A MEMORY LEAK AND MAKE YOUR APP GO LIMBO!!!
If it was me, I would implement the "onProgressUpdate()" for loaders like this:
public class MyLoader extends AsyncTaskLoader<Something> {
private Observable mObservable = new Observable();
synchronized void addObserver(Observer observer) {
mObservable.addObserver(observer);
}
synchronized void deleteObserver(Observer observer) {
mObservable.deleteObserver(observer);
}
#Override
public void loadInBackground(CancellationSignal signal)
{
for (int i = 0;i < 100;++i)
mObservable.notifyObservers(new Integer(i));
}
}
And in your Activity class
public class MyActivity extends Activity {
private Observer mObserver = new Observer() {
#Override
public void update(Observable observable, Object data) {
final Integer progress = (Integer) data;
mTextView.post(new Runnable() {
mTextView.setText(data.toString()); // update your progress....
});
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreated(savedInstanceState);
MyLoader loader = (MyLoader) getLoaderManager().initLoader(0, null, this);
loader.addObserver(mObserver);
}
#Override
public void onDestroy() {
MyLoader loader = (MyLoader) getLoaderManager().getLoader(0);
if (loader != null)
loader.deleteObserver(mObserver);
super.onDestroy();
}
}
remember to deleteObserver() during onDestroy() is important, this way the loader don't hold a reference to your activity forever. (the loader will probably be held alive during your Application lifecycle...)
Answering my own question, but from what I can tell, AsyncTaskLoader isn't the best to use if you need to update the UI.
In the class in which you implement LoaderManager.LoaderCallback (presumably your Activity), there is an onLoadFinished() method which you must override. This is what is returned when the AsyncTaskLoader has finished loading.
The best method is to use LiveData, 100% Working
Step 1: Add lifecycle dependency or use androidx artifacts as yes during project creation
implementation "androidx.lifecycle:lifecycle-livedata:2.1.0"
Step 2: Create the loader class as follow, in loader create in public method to set the livedata that can be observed from activity or fragment. see the setLiveCount method in my loader class.
package com.androidcodeshop.asynctaskloaderdemo;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;
import androidx.loader.content.AsyncTaskLoader;
import java.util.ArrayList;
public class ContactLoader extends AsyncTaskLoader<ArrayList<String>> {
private MutableLiveData<Integer> countLive = new MutableLiveData<>();
synchronized public void setLiveCount(MutableLiveData<Integer> observer) {
countLive = (observer);
}
public ContactLoader(#NonNull Context context) {
super(context);
}
#Nullable
#Override
public ArrayList<String> loadInBackground() {
return loadNamesFromDB();
}
private ArrayList<String> loadNamesFromDB() {
ArrayList<String> names = new ArrayList<>();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
names.add("Name" + i);
countLive.postValue(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return names;
}
#Override
protected void onStartLoading() {
super.onStartLoading();
forceLoad(); // forcing the loading operation everytime it starts loading
}
}
Step 3: Set the live data from activity and observe the change as follows
package com.androidcodeshop.asynctaskloaderdemo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<ArrayList> {
private ContactAdapter mAdapter;
private ArrayList<String> mNames;
private MutableLiveData<Integer> countLiveData;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNames = new ArrayList<>();
mAdapter = new ContactAdapter(this, mNames);
RecyclerView mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
countLiveData = new MutableLiveData<>();
countLiveData.observe(this, new androidx.lifecycle.Observer<Integer>() {
#Override
public void onChanged(Integer integer) {
Log.d(TAG, "onChanged: " + integer);
Toast.makeText(MainActivity.this, "" +
integer,Toast.LENGTH_SHORT).show();
}
});
// initialize the loader in onCreate of activity
getSupportLoaderManager().initLoader(0, null, this);
// it's deprecated the best way is to use viewmodel and livedata while loading data
}
#NonNull
#Override
public Loader onCreateLoader(int id, #Nullable Bundle args) {
ContactLoader loader = new ContactLoader(this);
loader.setLiveCount(countLiveData);
return loader;
}
#Override
public void onLoadFinished(#NonNull Loader<ArrayList> load, ArrayList data) {
mNames.clear();
mNames.addAll(data);
mAdapter.notifyDataSetChanged();
}
#Override
public void onLoaderReset(#NonNull Loader loader) {
mNames.clear();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Hope this will help you :) happy coding