Prevent JComboBox's Text Field to be Override - java

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.

Related

How to use autogenerated netbeans JFrame forms?

I want to develop a mini game and I struggle creating a Menu for this app. The Menu consists of 3 buttons (exit, rules, play) and I want to let the netbeans JFrame form designer to take care of it (you know, I just place the buttons, assign them functionality and style and the IDE creates the class code for me).
Now, the problem is that I do not know how to implement this code. It says that "This method is called from within the constructor to initialize the form.", so I guessed that I just had to do:
public Menu() {
create_and_show_menu();
}
private void create_and_show_menu() {
JFrame f = new JFrame("Menu");
new Sterge();
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
... but it didn't work out. Please tell me how to use that freakin' JFrame form, cause I haven't found anything online about that.
The auto-generated class code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author stoic
*/
public class Sterge extends javax.swing.JFrame {
/**
* Creates new form Sterge
*/
public Sterge() {
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() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton1MousePressed(evt);
}
});
jButton2.setText("jButton1");
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton2MousePressed(evt);
}
});
jButton3.setText("jButton1");
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton3MousePressed(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()
.addGap(138, 138, 138)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addContainerGap(189, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jButton1)
.addGap(42, 42, 42)
.addComponent(jButton2)
.addGap(46, 46, 46)
.addComponent(jButton3)
.addContainerGap(73, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jButton2MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jButton3MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
/**
* #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(Sterge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Sterge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Sterge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Sterge.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 Sterge().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
// End of variables declaration
}
The initcomponents() method initializes all of the Java swing components objects that your Front-End GUI uses, using the NetBeans GUI Builder. I see you are already using NetBeans GUI Builder and the IDE generated the code while you are designing,
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton1MousePressed(evt);
}
});
jButton2.setText("jButton1");
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton2MousePressed(evt);
}
});
jButton3.setText("jButton1");
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton3MousePressed(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()
.addGap(138, 138, 138)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addContainerGap(189, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jButton1)
.addGap(42, 42, 42)
.addComponent(jButton2)
.addGap(46, 46, 46)
.addComponent(jButton3)
.addContainerGap(73, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
So that is how the NetBeans IDE helping you to develop applications without typing more codes but with designing. Pretty easy huh :)
These swing components are automatically generated inside the above method whenever you make changes to the design of your GUI using the GUI builder.
You should not change any aspect of the above code within this method as this method is inextricably linked to the Front-End NetBeans GUI builder. If you change the code your Front-End also will be changed. But if you wish to change the code that is up to you to take care of it.
The initComponents(); method is called inside the constructor by default by NetBeans. And it is by default private. Running this initComponents(); method inside the Constructor will display the Front-End as soon as the application starts.
public Sterge() {
initComponents();
}
But you can call the initComponents(); method wherever you like (constructor or inside other methods). For Java, it is just like any other method.
When I come to your menu question, I don't see any JMenuBar and JMenuItems are used. If you need them you can read about how to use Menus from here. But I see there are 3 JButtons as you said there are three buttons in Menu. So I assume these are the 3 buttons that you are saying about.
Look at the following codes in your class.
private void jButton1MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jButton2MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jButton3MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
Suppose you need to print Hello World! in the console after you click the jButton1. Here is the place where you write the code. Inside the following method.
private void jButton1MousePressed(java.awt.event.MouseEvent evt) {
System.out.println("Hello World!");
}
Once you click the above button MouseEvent will be triggered and you will see the Hello World! text on the console. According to your details, there are 3 buttons for 3 functions (exit, rules, play). Writing the code is up to you. :)
private void jButton1MousePressed(java.awt.event.MouseEvent evt) {
// Code for exit the game writes here
}
private void jButton2MousePressed(java.awt.event.MouseEvent evt) {
// Code for show rules writes here
}
private void jButton3MousePressed(java.awt.event.MouseEvent evt) {
// Code for play the game writes here
}
If you look more carefully at the NetBeans-generated code, you will see that inside initComponents(); method there is this code,
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton3MousePressed(evt);
}
});
NetBeans use this structure to prevent edits on the standard code that could lead to incorrect event handling, allowing you at the same time to write the code you need to be executed when that event happens.
As you have used MouseListener I suggest don't use a MouseListener. A JButton is designed to be used with an ActionListener.
public void jButton3ActionPerformed(ActionEvent e) {
// Your code here
}
The generated code ActionListener by the NetBeans GUI Builder will be,
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
So I will stop writing from here as I can't cover all the points within this. The following links provide a very good quick start guide to the essentials of NetBeans GUI builder.
Introduction to GUI Building
Designing a Swing GUI in NetBeans
Hope this helps you. Happy Coding!

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.

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

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

How can I call one GUI class from another GUI class?

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.

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.

Categories