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.
Related
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.
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
In my class file, I am making a GUI appear, and what I am trying to accomplish is when you hit the finish button, a different GUI (that I made in another class) appears, while the old one closes.
This is the GUI I want to appear -
package my.contacteditor2;
import java.util.ArrayList;
/**
*
* #author Prox
*/
public class ContactEditorUI_1 extends javax.swing.JFrame {
String disease1;
String disease2;
String disease3;
String disease4;
String disease5;
int ChromeNum=0;
String Chrome;
ArrayList<String> diseases = new ArrayList<String>();
/**
* Creates new form ContactEditorUI
*/
public ContactEditorUI_1() {
initComponents();
setLocationRelativeTo(null);
}
public String resultsDisplayed (String [] disease, int number, boolean [] haveDisease) {
return Chrome;
}
/**
* 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() {
jButton2 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton2.setText("Exit");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Trebuchet MS", 0, 36)); // NOI18N
jLabel1.setText("Results");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 870, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addContainerGap(25, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
/**/
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* 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(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ContactEditorUI.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 ContactEditorUI_1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
In my original class, I cant figure out how to call it successfully so that the GUI appears. I have tried making run its own method, and calling it in the other class with ContactEditorUI_1.run();.
I have also tried ContactEditorUI_1.ContactEditorUI_1() (the main constructor).
I'm sure there is a simple way to do this, but I'm having some trouble finding it. Does anyone have any good ideas?
It's usually not much fun for the user to be barraged by a succession of new windows, and most applications when faced with this problem show just one window, but swap views in that window, for instance a game that first shows set up views and then the main game, all in one window. Another option is to show one main window, and then if you need to gain information from the user in a modal fashion -- in a way where the program flow must stop until the information is returned -- then using a modal dialog such as a modal JDialog or JOptionPane.
The key to any and all of this (in my opinions), whether you go with either of the two approaches above, or even if you want to show a succession of main windows, is to gear your Swing GUI programs towards creating JPanels not JFrames. If you do this, then you can place your JPanel whenever needed wherever you want, be it in its own JFrame, in a dialog, swapped in a CardLayout (the view swapping mentioned above), as a tab in a JTabbedPane or even in a JOptionPane.
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
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.