How to Hide JPanel and Open another one in other Java FIle? - java

I'm newbie in java GUI , so i'm facing a problem right now ...
i've created a GUI using Netbeans GUI Builder ..
i've Created a file called MainUI.java and gdUI.Java
the MainUI.java contains the frame and buttons in which if a button is clicked the Jpanel Hides and opens the Panel from gdUI.java
here's the code i've done so far :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jPanel1.setVisible(false);
}
and gdUI code is :
package GUI;
public class gdUI extends javax.swing.JPanel {
/**
* Creates new form gdUI
*/
public gdUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setBackground(new java.awt.Color(255, 153, 51));
setMaximumSize(new java.awt.Dimension(600, 500));
setMinimumSize(new java.awt.Dimension(600, 500));
setPreferredSize(new java.awt.Dimension(600, 500));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 600, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
);
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
}
when i click the button , i successfully hided the current JPanel , how can i add the other files new one ?
Thanks In Advance

The way you want to accomplish this task is using a CardLayout as pointed out by trashgod. This will allow you to switch between views, with simple Cardayout commands like next(), previous() and show(), the last allowing to show any particular component/view by name.
You can see the Oracle tutorial on How to Use CardLayout
You can see How to Use CardLayout with Netbeans GUI Builder
You can see how to drag and drop other panel forms here

Related

How to update an image in a Java GUI

I have a GUI with several buttons and I'm using NetBeans GUI Builder to do.
At the click of one of these I would like for it to open another frame containing a picture.
So I associate a listener (actionPerformed) the button and when clicked it opens actually post the new frame.
In the new frame I waxed a JLabel and then I associate the image of the label. I saw that to do that NetBeans generates this code:
label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/tree.png")));
My problem is that the picture is overwritten several times during the execution of the program is not changed yet in the frame.
That is, in the new frame is always displayed an old version of the image.
How can I do so that the image is always up to date?
Thank you very much
The Code:
package View;
import Controller.Util;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class AlberoIpotesi extends javax.swing.JFrame {
/** Creates new form AlberoIpotesi */
public AlberoIpotesi() {
initComponents();
remove(label);
revalidate();
repaint();
Decifra.sessioneDec.toString(".../src/img/tree");
revalidate();
repaint();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
scroll = new javax.swing.JScrollPane();
label = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Albero delle ipotesi");
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setText("Albero delle ipotesi");
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/tree.png"))); // NOI18N
label.setVerticalAlignment(javax.swing.SwingConstants.TOP);
scroll.setViewportView(label);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 342, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addContainerGap(29, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(25, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void start() {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AlberoIpotesi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AlberoIpotesi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AlberoIpotesi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AlberoIpotesi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AlberoIpotesi().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
public static javax.swing.JLabel label;
public static javax.swing.JScrollPane scroll;
// End of variables declaration
}
I'd seperate the creation of the icon and the setIcon on the JLabel, like so:
ImageIcon icon = new ImageIcon("path/to/picture.png");
label.setIcon(icon);
That way you can change the icon's image later and update the label
icon = new ImageIcon("path/to/new_picture.png"); // Changes the icon
label.setIcon(icon); // Updates the label's icon
So basically what I understand is that you have a button which creates a new instance object of the frame you wish to display right? Then you have an image stored in a particular location of your project where you will recall the object to display the updated image as you say?
I am unaware of how you choose to launch your frame. But what I can suggest is that you make use of a parametrized constructor to change your image each time(if required) the frame is called.
https://www.dropbox.com/s/mpqvy9hgsvsgq9t/PeanutsAndPretzels.zip
I am not sure of the terms and conditions of stackoverflow and external project files. But I compiled something which may or may not help you. Give it a bash to get an idea perhaps.

Text fields become unresponsive while running Java Swing JFrame after re-opening NetBeans

I created a JFrame form using Java Swing in NetBeans. It contains some text fields, some combo boxes and a button to navigate to the next form. Everything works fine until I close and re-open NetBeans. Now when I run the form only the text fields become unresponsive. The combo boxes and the button work correctly. I tried using setEditable(), setFocusable() and requestFocusinWindow() with the text fields but the output hasn't changed. Please help me.
package Hora.GUI;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class InputJFrame3 extends javax.swing.JFrame
{
public InputJFrame3()
{
initComponents();
numberJTextField.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
numberJTextField.setForeground(Color.black);
}
});
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
numberJLabel = new javax.swing.JLabel();
numberJTextField = new javax.swing.JTextField();
nextJButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("HORA");
setFocusableWindowState(false);
numberJLabel.setText("Number");
nextJButton.setText("next >");
nextJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextJButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(nextJButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(numberJLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numberJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(numberJLabel)
.addComponent(numberJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nextJButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void nextJButtonActionPerformed(java.awt.event.ActionEvent evt)
{
//GEN-FIRST:event_nextJButtonActionPerformed
number=Integer.parseInt(numberJTextField.getText());
Boolean mistake=false;
if(number<1 || number>249)
{
mistake=true;
numberJTextField.setForeground(Color.red);
}
if(!mistake)
setVisible(false);
}//GEN-LAST:event_nextJButtonActionPerformed
public int getNumber()
{
return number;
}
private int number;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton nextJButton;
private javax.swing.JLabel numberJLabel;
private javax.swing.JTextField numberJTextField;
// End of variables declaration//GEN-END:variables
}
package Hora.GUI;
public class Run
{
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
InputJFrame3 frame = new InputJFrame3();
frame.setVisible(true);
}
});
}
}
Your problem is here:
setFocusableWindowState(false);
Doing this prevents the JTextField from getting focus and being usable. I suggest that you not do this.
Also, I agree with camickr, that you should not use an IDE to create your sscce. Just add your components to a simple JPanel which uses FlowLayout by default, something like:
nextJButton.setText("next >");
nextJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextJButtonActionPerformed(evt);
}
});
JPanel panel = new JPanel();
panel.add(numberJLabel);
panel.add(numberJTextField);
panel.add(otherJTextField);
panel.add(nextJButton);
getContentPane().add(panel);
pack();
}// </editor-fold>//GEN-END:initComponents
Also and again, your program looks as if it's swapping JFrames which generally considered a weak design. Instead gear your code to create JPanel "views" and have your GUI swap views with a CardLayout. If you must show a detail window, then use a JDialog.
Edit 2
In a comment you state:
But that part is in the generated code. I opened the java file in Wordpad and modified it. It works now. Is there any other way to do it using the IDE? Thanks a lot Mr. Hovercraft and Mr. Camickr for helping me out. I'm doing this a hobby project for my grandpa who wants to automate his astrology calculations.
I think it is fair to say that most of the main Swing advisers on this site (at least the ones that that I am familiar with) create their Swing code by hand. Don't get me wrong, we use IDE's, but we don't use an IDE's drag-and-drop tool in creating our Swing code. The Swing Tutorials will help you learn how to do this. In particular, please have a look at Lesson: Laying Out Components Within a Container the section.
Note that even if you do end up using a Swing code generator such as NetBeans's Matisse tool, it won't hurt you to learn how to do some hand coding since the knowledge gained will be directly applicable in your work with the code-generating tool.

Zero Width Height jPanel on start

Why does the jPanel return 0 for the height and width when it starts and how can I get the right values on start.
import javax.swing.JPanel;
class ZeroJPanel extends JPanel {
/**
* Creates new form ZeroJPanel
*/
ZeroJPanel() {
initComponents();
System.out.println( this.getHeight() );
}
public static void main(String Args[]) {
new ZeroJPanel();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
}
The panel returns 0, 0 because, quite simply, that is the default value.
When you add the panel to a frame, and call pack() on the frame, that will calculate the correct (preferred) size and set it. Until then, you won't be able to find the size because it hasn't been calculated.
Why do you need these values? If you can explain the problem in broader terms, we may be able to help you.

Inheritting from custom JPanel using NetBeans GUI Builder

ContainerPanel is a custom JPanel class using a BorderLayout. The SOUTH contains a JPanel with a button. I want the CENTER to be an instance of another custom JPanel, say AbstractPanel, which provides an abstract method which will be called when the button is clicked. I also want to set this JPanel programmatically (at run-time). So far, I can do all of this as you can see in the following code (some of which is generated by the NetBeans GUI Builder):
package jpaneldemo;
import java.awt.BorderLayout;
public class ContainerPanel extends javax.swing.JPanel {
public ContainerPanel() {
initComponents();
}
public ContainerPanel(AbstractPanel abPanel) {
initComponents();
this.abPanel = abPanel;
this.add(this.abPanel, BorderLayout.SOUTH);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
private void initComponents() {
buttonPanel = new javax.swing.JPanel();
okButton = new javax.swing.JButton();
setLayout(new java.awt.BorderLayout());
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
buttonPanel.add(okButton);
add(buttonPanel, java.awt.BorderLayout.PAGE_END);
}
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
this.abPanel.abstractMethod();
}
// Variables declaration - do not modify
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton okButton;
// End of variables declaration
private AbstractPanel abPanel = null;
}
I also created the AbstractPanel class:
package jpaneldemo;
public abstract class AbstractPanel extends javax.swing.JPanel {
public AbstractPanel() {
initComponents();
}
protected abstract void abstractMethod();
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}
// Variables declaration - do not modify
// End of variables declaration
}
Now I want to create subclasses of this AbstractPanel class which I can edit in the NetBeans GUI. Typically, I right-click on a package name in the Projects window and then navigate to "New -> JPanel..." to create a custom JPanel. How do I get AbstractPanel to appear in the "New" menu so that I can edit the new class with the NetBeansGUI Builder? Or is there another way to accomplish the same thing?
If your intention is to provide a "template" component that can then be added to the palette and included in other containers, then yes you can.
Have a read through FaqFormCustomContainerBean
The basic idea (apart from creating a BeanDescriptor is you will need to provide a "content" panel of some kind, where additional content can be added at design time.
Now, if you're interested in providing a custom template, that's something I've not done before.
You could try reading through http://netbeans.org/competition/win-with-netbeans/customize-java-template.html. It may be a little out of date, but might help you in the right direction

Prevent JComboBox's Text Field to be Override

I realize, if I didn't not include line
jComboBox1.addItem("Cause Text Field To Override");
When I type in "A" in JComboBox's text field, "A" will shown in JComboBox's text field.
However, If I include the addItem code, JComboBox's text field will be override. (The lower boundary line also dissapear, not sure why)
I wish to able to addItem, and showPopup without override the content in JCombBoBox's text field. May I know how I can do so?
package javaapplication5;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
/**
*
* #author yccheok
*/
public class NewJDialog extends javax.swing.JDialog {
/** Creates new form NewJDialog */
public NewJDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
jComboBox1.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
jComboBox1.addItem("Cause Text Field To Override");
jComboBox1.showPopup();
}
});
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jComboBox1.setEditable(true);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Hello", "World", "Bye" }));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(124, 124, 124)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(92, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(76, 76, 76)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(204, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
NewJDialog dialog = new NewJDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JComboBox jComboBox1;
// End of variables declaration
}
It's been a long time since I've done Swing, but I suspect that when you do your AddItem is causing a contentsChanged callback as the combo box is ListDataListener, and that based on that the combo-box is re-setting the selected item to the first item in its model.
I'd suggest you look at what JComboBox does in its implementation of ListDataListener and debug a bit.
However it looks like what you're trying to do goes against the natural swing of swing a bit - i.e. typing a key changes what is in the model by adding to the model.
Rather than using keyEvents on the combo-box, you would be better off adding listeners to the model that then manipulate results in the way you need.

Categories