JDialog won't show in design tab - java

I'm working with the Window Builder plugin for Eclipse.
When I execute the below code it shows the JDialog correctly. I was expecting the JDialog to show in the design tab (at design time) as well, but it won't.
package testshowjdialog;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MyJDialog extends JDialog {
private static final long serialVersionUID = 1L;
public MyJDialog(JFrame parent) {
super(parent, true);
setTitle("A Title");
JButton button = new JButton("Test");
add(button);
setSize(100, 100);
}
/**
* #wbp.parser.entryPoint
*/
public static void main(String [] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyJDialog dialog = new MyJDialog(new JFrame());
dialog.setVisible(true);
}
});
}
}
Any idea why?

Try removing the comment above the main-method specifying the entryPoint for the WindowBuilder.
This comment is usually used when a window/dialog is created not as its own class, but in a method of another class. Think of a method showCustomDialog() that creates and shows the dialog, but the class does lots of other stuff in other methods. Then, one can tell WindowBuilder where it should start parsing the code to detect which window/dialog it should show for editing.
Most likely, WindowBuilder is not able to correctly parse your main-method and does not recognize what window/dialog you try to create, and thus only shows an empty frame. Removing the entrypoint-comment will WindowBuilder make parse the Constructor of your class, which should work out better.

Related

Java components are invisible when swing app is run as APPLET

Respected all,
I am making a Swing-application window in ECLIPSE. When I run the program as 'JAVA-Application' the program functions well. However when I try to run the program as "Java_applet" the components like 'command button', 'textbox' are invisible.
I am entirely new to Java. I had previously worked on C#. Kindly please help me.
import java.awt.EventQueue;
import java.applet.*;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import java.awt.BorderLayout;
public class sa extends Applet{
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
sa window = new sa();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public sa() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JRadioButton rdbtnNewRadioButton = new JRadioButton("New radio button");
frame.getContentPane().add(rdbtnNewRadioButton, BorderLayout.CENTER);
}
}
You can't just have your class extend Applet and expect that that is all that is necessary for it to behave like a proper Applet. You need to give the class a proper init method and build the GUI from within this method. But most importantly you will need to read an Applet tutorial, any decent tutorial should do. Myself, I'd have my GUI extend JPanel, build the GUI in its constructor, and then I could use this JPanel in a JApplet or JFrame as needed.
As Andrew aptly notes in comment,
I think the OP should also dump the entire 'applet' part of it and develop the JFrame with an idea to launching it from a link using Java Web Start. At least then it would have a better chance for working for users of Chrome and FireFox (which are both planning to remove all support for applets).

Cant' intercept the JFrame termination event by the shutdown() method in a SingleFrameApplication, why?

I am pretty new in Java Swing development and I have the following problem.
I am working on an application that use Swing JDesktop framework.
So I have the following 2 classes:
1) GUI.java:
package com.test.login2;
import org.jdesktop.application.SingleFrameApplication;
public class GUI extends SingleFrameApplication {
// Estensione di JFrame:
private MainFrame mainFrame = null;
#Override
protected void startup() {
System.out.println("GUI ---> startUp()");
mainFrame = new MainFrame();
mainFrame.setVisible(true);
}
// Save session state for the component hierarchy rooted by the mainFrame:
#Override
protected void shutdown() {
System.out.println("ShutDown event intercepted by the GUI ---> sutdown() method");
}
public static void main(String[] args) {
System.out.println("GUI ---> main()");
/* Creates an instance of the specified Application subclass (SingleFrameApplication),
* sets the ApplicationContext application property, and then calls the new Application's startup method.
*/
launch(GUI.class, args);
}
}
As you can see in this class there is the main() method that simply perform this operation:
launch(GUI.class, args);
Reading on the official docimentation: launch() doc
Creates an instance of the specified Application subclass, sets the
ApplicationContext application property, and then calls the new
Application's startup method. The launch method is typically called
from the Application's main. The applicationClass constructor and startup methods run on the event dispatching thread.
So the startup() method is executed and there is created and show a new MainFrame object
2) So this is the MainFrame code (it simply extends a classic Swing JFrame):
package com.test.login2;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import com.test.login.LoginFrame;
import net.miginfocom.swing.MigLayout;
public class MainFrame extends JFrame {
private static final int FIXED_WIDTH = 1000;
private static final Dimension INITAL_SIZE = new Dimension(FIXED_WIDTH, 620);
private final Action actionLogOut = new AbstractAction() {
{
putValue(Action.NAME, ("LogOut"));
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("MainWindows ---> actionPerformed()");
JButton button = (JButton)e.getSource();
Window window = SwingUtilities.windowForComponent(button);
//window.setVisible(false);
//window.dispose();
}
};
public MainFrame() {
super();
setPreferredSize(INITAL_SIZE);
setResizable(false);
setTitle("My Application");
setLayout(new MigLayout("fill"));
add(new JButton(actionLogOut)); // Add the LogOut JButton to the current MainFrame object
pack();
setLocationRelativeTo(null); // Center the window
}
}
At this stage this is not very important the presence of the JButton and of the relative listener.
My problem is the following one:
As you can see in the GUI.java class is definied a shutdown() method (that is definied in the SingleFrameApplication abstact class).
shutdown() method doc
Reading the documentation:
Save session state for the component hierarchy rooted by the
mainFrame.
So the main() method of GUI.java class perform the operation that execute the startup() method that create and show the MainFrame object (and untill here it is clear)
Then I would that when I click on the X button (the button that close the JFrame), the shutdown() method (of the GUI.java class) is performed. I can't intercept this event and this is a big problem for me
Someone can help me?
Tnx
Andrea
I use a window listener something like this. You can use this right in the constructor for your MainFrame class
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
//do all your saving
System.exit(0);
}
});
do note that the System.exit(0); command will close your entire application. So this exact code shouldnt be used in a situation where you want to just close a jframe and not close the entire application.

EDT on Swing (for Dummies)

So, I'm just working on a little game, which works quite fine, except for the GUI. Basically, I need to modify the GUI when clicking a button. I realize that I have to run my code on the EDT to do so, using this code:
EventQueue.invokeLater(new Runnable () {
#Override
public void run() {
// some code
}
});
I just don't now which part of my code is concerned by this. The part where I create the GUI (the constructor of my class)? Or only the part where i modify the values (in that case Listener.actionPerformed())? Actually I tested bot of this, neither worked.
Now what I want to know is how do I modify the following code to update the Button when i click it? Do I have to embed parts of it in the code above or am I completely wrong?
package edttest;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class EDTtest {
public static void main(String[] args) {
GUI gui = new GUI ();
}
private static class GUI extends JFrame {
int x;
public GUI () {
x = 0;
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JButton button = new JButton (String.valueOf(x));
button.addActionListener(new Listener ());
JLabel label = new JLabel (String.valueOf(x));
add (label, BorderLayout.NORTH);
add (button);
pack();
setVisible (true);
}
private class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
x++;
System.out.println (x);
}
}
}
}
Whether or not you execute this code on the EDT will do nothing to your label. It is not because you increment x that the label will update itself. You need to call label#setText with the updated value.
Concerning your question around the EDT. All access/modifications/creation/... of Swing components should happen on the EDT. This means you should wrap the contents of your main method in an SwingUtilities#invoke.... Every event that is triggered through the UI (e.g. the click on a button) will already be processed on the EDT. So no need to explicitly schedule a Runnable on the EDT in your listener.
When in doubt, you can always check whether you are on the EDT by using EventQueue#isDispatchThread.
I would also suggest to read the Concurrency in Swing tutorial

Displaying JFrame

I'm having issues figuring out how to open one window when another closes if the other window is initiated within a sub class. Here is the clumsy code I am trying to use, but it halts the setting visible of the sub classe's window. Perhaps due to it being within an action event or perhaps it is halting the main thread.
tutorial = new tutorialWindow();
this.setVisible(false);
tutorial.setLocationRelativeTo(null);
tutorial.setVisible(true);
tutorial.setCurrentUser(users.getCurrentUser());
while(tutorial.isOpen() == true ) {
}
this.setVisible(true);
users.updateUser(tutorial.getCurrentUser());
My thoughts were that it would just get stuck in the section of code until the other window closes and would then appear again when the tutorialWindow has a Open boolean set to false due to it breaking the while loop.
Im sure this is a matter of using correct threads, or perhaps the various notify methods but as of now I am not sure how to do that.
You could do it using WindowListener. In the following sample WindowAdapter implements WindowListener and I just override the public void windowClosed(final WindowEvent e) method, opening the second window.
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TestJFrame {
public static void main(final String args[]) {
JFrame jFrame1 = new JFrame();
jFrame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jFrame1.add(new JLabel("First JFrame"));
jFrame1.pack();
final JFrame jFrame2 = new JFrame();
jFrame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jFrame2.add(new JLabel("Second JFrame"));
jFrame2.pack();
jFrame1.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(final WindowEvent e) {
jFrame2.setVisible(true);
}
});
jFrame1.setVisible(true);
}
}

Element inserted into custom ListModel is automatically selected if between two selected values

I've noticed is that when an element is added to a JList and the element happens to fall within a range of values that are selected, it ends up being selected by default. In fact, if an element is added just above a selected value it is added to the selection.
I've tried looking at the JList code (in the open JDK6) and the BasicListUI code, but I'm having trouble teasing out the details of why this happens or what I need to do to fix it.
I'm considering supplying a custom SelectionModel, as that would be a sensible place to do some of the other work in my application, but I'm afraid that might make the problem worse, or harder to fix. Does anyone know why this happens? What I can do to fix it?
I've created this example that demonstrates the issue:
package jlistsscce;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
public class JListSSCCE extends JPanel
{
private final JList list;
private ScheduledExecutorService ses;
public JListSSCCE()
{
list = new JList();
list.setModel(new DefaultListModel());
ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new NewElement(), 100, 100, TimeUnit.MILLISECONDS);
add(list);
}
private static void createGui()
{
// create new JFrame
JFrame jf = new JFrame("JListSSCCE");
// this allows program to exit
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// You add things to the contentPane in a JFrame
jf.getContentPane().add(new JListSSCCE());
// size frame
jf.pack();
// make frame visible
jf.setVisible(true);
}
public static void main(String[] args)
{
// threadsafe way to create a Swing GUI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
createGui();
}
}
);
}
private class NewElement implements Runnable
{
int n = 0;
#Override
public void run()
{
((DefaultListModel)list.getModel()).add((int)Math.floor(Math.sqrt(n)), ("hey"+n));
n++;
}
}
}
This isn't the problem but I believe you should be using a Swing Timer instead of an Executor so the code get executed on the EDT.
Yes the problem is the selection model. The last time I looked at the code I found it rather confusing, so I'm not sure you want to play with it.
The only thing I can think of is to make sure you are using the multiple selection interval. Then after inserting an elemnt you check to see if the element is selected. If it is then you remove the selection for that element.

Categories