Displaying a JFrame as the result of a JButton click? - java

I am trying to create a JPanel to display when a user clicks a button within my main JFrame. In Netbeans I first used the wizard to add a new JPanel to my project, I then used the GUI creator to fill in all the content. I am not trying to display the JPanel with the following code
private void m_jbShowSelAccResultsActionPerformed(java.awt.event.ActionEvent evt)
{
Account selAcc = getSelectedAccount();
if(selAcc != null)
{
AccountView accPanel = new AccountView(Account.getDeepCopy(selAcc));
accPanel.setVisible(true);
}
else
ShowMessage("Please select an account to view");
}
But nothing happens, no error is thrown and the JPanel is not shown. So I then changed the JPanel to a JFrame (Netbeans didn't complain). When I try again with the same code I receive the error GroupLayout can only be used with one Container at a time.
How can I display my JPanel/JFrame?

To change views within a Swing GUI, use a CardLayout as this is a much more robust and reliable way to do this.
Don't try to blindly "change a JPanel to a JFrame". It looks like you're just guessing here.
GroupLayout can't be reused as the error message is telling you. Likely this error comes from the point above. If you avoid trying to make a JFrame out of a JPanel, the error message will likely go away. As an aside, GroupLayout is not easily used manually, especially if you're trying to add components to an already rendered GUI.
So for instance, if your program had a JPanel say called cardHolderPanel, that used a CardLayout, this held by a variable say called cardLayout, and you've already added a "card" JPanel to this holder for accounts, say called accPanel, and if the accPanel had a method to set its currently displayed account, say setAccount(Accoint a), you could easily swap views by calling the CardLayout show(...) method, something like:
private void m_jbShowSelAccResultsActionPerformed(java.awt.event.ActionEvent evt) {
Account selAcc = getSelectedAccount();
if(selAcc != null) {
accPanel.setAccount(Account.getDeepCopy(selAcc));
cardLayout.show(cardHolderPanel, "Account View");
}
else {
showErrorMessage("Please select an account to view");
}
}

Related

How do you add a jFrame to your main class in Netbeans?

So I have made a Jframe with a lot of elements and buttons and things in it, but I am new to using NetBeans. Upon creating the java application a main class.java was created and upon adding the jframe another jframe.java was created. How do I get the main class to open, read, and run my jframe.java? I can upload the specific code if need be.
Thanks in advance
To call a certain method from another class, you must first create a new object for that class, like this:
Jframe frame = new Jframe();
frame.setVisible(true); //or whatever the method is in jframe.class
Maybe rename the actual class name from jframe to something like frameone. I've heard that naming classes the same as classes in the Java API will cause trouble.
Or, you could put it all in one class, with either two separate methods or put it all in the main method. If this doesn't help, then please paste the exact code on pastebin.org and give a link.
Look at this sample example and learn how to set frame visible
import java.awt.*;
import javax.swing.*;
public class exp{
public static void main(String args[]){
JFrame jf=new JFrame("This is JFrame");
JPanel h=new JPanel();
h.setSize(100,100);
h.add(new JButton("Button"));
h.add(new JLabel("this is JLabel"));
h.setBackground(Color.RED);
jf.add(h);
jf.pack();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}
Useful Links
Designing a Swing GUI in NetBeans IDE
Creating a GUI With Swing (As #MadProgrammer Commented)
Learning Swing with the NetBeans IDE
I'm new to this, but I got a form up. Woo hoo!
1) The project created my main function in japp1.java
2) I created a JFrame, file jfMain.java
3) While there was probably a way to reference it as it was, I didn't see how right away, so I moved it to a peer level with the japp1 file, both in a folder called japp1 which will cause them to get built together, having the same parent reference available.
src\
japp1\
japp1.java
jfMain.java
4) Then instead of creating a generic JFrame with a title, I created an instance of my class...
5) I gave it a size...
7) Then showed it...
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new japp1.jfMain();
frame.setPreferredSize(new Dimension(700, 500));
frame.pack();
frame.setVisible(true);
}
I had already put some code in my jframe... to show a messagedialog with JOptionPane from a mouseclick event on a button and set some text for some textfields.
Hope that helps.

Pull down searching window in Java

I have to create a searching window, like a google browser window. It must have a pull down list containing similar results, which is populated from a database.
I am trying to adjust a JCombobox but this has caused ​​me a lot of trouble. Is there a better way to do this? (Perhaps something like this already exists in Java.) If not, can anyone advise me on how to achieve my goal?
create JTextField with keyboard event to show the popup window on key realeased,
Example:
jTextField2.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
showPopup(evt);
}
});
void showPopup(java.awt.event.KeyEvent evt) {
JPopupMenu popup = new JPopupMenu();
popup.setLightWeightPopupEnabled(false);
popup.setBorder(BorderFactory.createLineBorder(Color.black));
popup.setLayout(new BorderLayout());
popup.setSize(this.getPreferredSize());
popup.setPreferredSize(this.getPreferredSize());
popup.pack();
popup.setOpaque(false);
// create panel that contains the search result
popup.add(BorderLayout.CENTER, <YOUR PANEL WITH THE RESULT>);
popup.setPreferredSize(new Dimension(jTextField2.getWidth(),250));
<SEARCH PANEL>.setPreferredSize(new Dimension(jTextField2.getWidth(),250));
popup.show(jTextField2, 0, jTextField2.getHeight());
}
i have to do searching window like google browser window. It must have pull down list with similarities results that comes from database. I trying to adjust JCombobox but this made ​​me a lot of trouble.
Maybe not true, I'd to use AutoComplete JComboBox / JTextField

How to close JFrame?

I have the main application frame. If user clicks the button he gets a new frame which has some chart in it. Now if I want to close that chart both chart and main application closes. How can I distinguish those two closings. Certainly I don't want my application to be closed after closing the frame in which I put chart.
Here's the code of the chart frame.
chartBttn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final ShowChart sc = new ShowChart("Reserve Selection", getUtilExperiments() );
sc.pack();
RefineryUtilities.centerFrameOnScreen(sc);
sc.setVisible(true);
sc.setDefaultCloseOperation(ShowChart.DISPOSE_ON_CLOSE);
}
});
You can use the dispose() method. Or you can call setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); on the JFrame.
If I understood you correctly on your new JFrame build a method for your close button or X window button with:
setVisible(false);
dispose();
Otherwise please post your code on creating the new JFrame etc.
Certainly I don't want my application to be closed after closing the frame in which I put chart.
1) don't create lots of JFrames on the fly, create JFrame only once and re-use that for next usage(s), then
call only for visibility setVisible(false/true) with setDefaultCloseOperation(JFrame.NOTHING_ON_CLOSE)
or very simple workaround
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
2) or JDialog with setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE)
3) NOTICE: but in this case isn't possible close the current JVM instance, you have to add JButton or JMenu/JMenuItem which accelerate for System.exit(1)
simply use super.dispose(); for closing previous jframe

How to process forms in Java?

Using Swing in Java I wrote a form containing radio buttons, text fields and so on. In the very end I have a "Submit" button.
Now I want to "send" the information given by the user to the program. How do I do that? Is there a good tutorial about that?
Is it kind of similar to PHP? (I am asking just because I know how to do it in PHP. To avoid confusions I probably need to mention that I do NOT program a web application).
Processing data in Swing is way different from the typical web REQUEST/RESPONSE paradigm.
To Take something you may know, it's more in the fashion of Javascript actions in an HTML page : each time user performs an operation, one or more events are sent, and the application developper can update application content according to it.
In your case, if you register an ActionListener to the button, it will be called each time button is clicked. You'll then have the possibility to perform any operation you want.
But that's not all !
Each time a component is keyboard focused, or receives the mouse, events are sent, as well as when a key is stroked or when widget's model is updated.
I would really suggest you to read documents such as Swing tutorial (which dives in greater details than I could do in 1 month).
Not completely sure what you mean by "send to the program". You are in the program so I assume that you have a dialog that renders this form? Just pass the dialog the object that you want to use to store the data. For example, your dialog's constructor can take an argument.
public class MyDialog extends JPanel {
private UserInfo userInfo;
private JTextField name;
/**
* The main area of the dialog.
*/
protected JPanel panel;
public MyDialog(UserInfo userInfo) {
this.userInfo = userInfo;
}
public showDialog() {
// Some code to create the form which it looks like you already know how to do
// Create a name field
JLabel nameLabel = new JLabel("Name:");
panel.add( nameLabel );
JButton submit = new JButton("Submit");
submit.addActionListener( new ActionListener() {
public void actionPerformed (ActionEvent event)
{
this.userInfo.setName(name.getText().trim());
} } );
panel.add( submit );
}
}

How show my application delay with JProgressBar?

I wrote a simple application and I want show delay of it with JProgressBar Plese help me ;
I want show JProgressBar with Joptionpane , with a cancel button and it should be modal
this is my source code :
class CustomFrame extends JFrame {
private JProgressBar progressBar;
public CustomFrame() {
long start = System.currentTimeMillis();
myMethod();
this.getContentPane().setLayout(null);
this.setSize(200, 200);
//JOptionPane. ?????
this.setTitle("JFrame");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
long end = System.currentTimeMillis();
System.out.print("\nTime: " + (end - start));
}
public void myMethod(){
try {
java.io.File file = new java.io.File("i://m.txt");
BufferedReader input =
new BufferedReader(new FileReader(file));
String line;
while ((line = input.readLine()) != null) {
if (line.indexOf("CREATE KGCGI=") != -1 ){
System.out.println(line);
}
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
}
Thanks ...
There are a couple things that you will need to do to get this to work:
You should be aware of threading issues in Swing. Your GUI painting should be done on the EventDispatchThread and disk I/O should be done in a worker thread. See this tutorial, the SwingWorker JavaDoc, and SwingUtilities.invokeLater for more detail
You will then want to get the size of your file (file.length())to determine how to scope your progress bar (myProgressBar.setMaximum(length))
When you iterate over the lines in your file, you will want to trigger an update to your progress bar (myProgressBar.setValue(myProgressBar.getValue()+lineLength)).
A couple points by way of critique:
your constructor shouldn't go off and do all of your work (ie load your file and pop up an option pane with the ability to cancel. the constructor should just do the work needed to create the object. you might want to consider having your constructor create your class, and then have the work that needs to be done to be called separately, or within something like an init() method.
It isn't clear what you are doing with the JFrame as superclass. JOptionPane is a class that will pop up a very basic modal dialog with some text, maybe an icon or input field. It isnt a panel that is embedded in a dialog.
As JOptionPane is a very basic construct for creating a basic message dialog, it might be easier to use a JDialog, which can also be made modal. JDialog will allow you to add buttons as you please, where as a standalone JOptionPane will require you to use Yes/No, or Yes/No/Cancel or OK/Cancel etc.
If you still want to use JOptionPane, and only show a cancel button, you can instantiate a JOptionPane (as opposed to using the utility show* methods), with the progressbar as the message, and the JOptionPane.CANCEL_OPTION as the optionType param. You will still need to put this into a JDialog to make it visible. See this tutorial for more details:
JOptionPane (constructor)
Creates a JOptionPane with the specified buttons, icons, message, title, and so on. You must then add the option pane to a JDialog, register a property-change listener on the option pane, and show the dialog. See Stopping Automatic Dialog Closing for details.

Categories

Resources