Paint method in a class, on a Jpanel, design mode at Netbeans - java

I've been trying to program an applet with Netbeans able to draw some graphics into a jPanel, as you can see:
![enter image description here][1]
Applet form:
package Experimento2;
import javax.swing.*;
import java.awt.*;
public class Experimento2 extends javax.swing.JApplet {
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
//ZonaGrafica zg = new ZonaGrafica();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 466, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 259, Short.MAX_VALUE)
);
jButton1.setText("jButton1");
jButton2.setText("jButton2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(23, 23, 23))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(85, 85, 85)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(37, 37, 37))
);
//jPanel1.add(zg,BorderLayout.CENTER);
//zg.repaint();
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
And the ZonaGrafica class, which is in the same package:
package Experimento2;
import javax.swing.JApplet;
import java.awt.*;
public class ZonaGrafica extends JApplet{
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.red);
g.fillOval(45, 65, 34, 54);
g.fillOval(45, 120, 34, 54);
g.fillOval(45, 180, 34, 54);
}
}
But unfortunately, nothing happens when I run the jApplet form. In the place where the paint method is supposed to draw some red ovals, nothing is shown. I have no clue to solve this issue, and I would be grateful to whom could help me to solve it..

Don't override paint. Try with paintComponent instead.
Your ZonaGrafica object is never instantiated(commented). I hope you are at least doing that.
In addition to that, you are trying to ad a JApplet (ZonaGrafica) to another JApplet (Experimento2). Refactor ZonaGrafica and let it extend JPanel or JLabel.

The form editor “would” work with either overriden paint or paintComponent, though Heisenbug's suggestion to make it paintComponent is still a good one.
From reading your code I think that you simply hit the “customise code” button added a few lines and thought that would sort it. It doesn't, because:
GroupLayout doesn't work that way. It is not at all kind to the someContainer.add() approach of adding UI.
Speaking of which, the Border layout constant makes no sense.
And at design time the code isn't even run, anyway. The form editor uses an XML document to track what components to instantiate and how, so you wouldn't see your custom paint logic even if you did something like adding a JPanel and customising the constructor to read e.g. jPanel3 = new ZonaGrafica();. Which brings me to:
The only way to make the component show up properly at design time is to have it compiled first, then added to the form through the “Add Java Bean” feature of the editor. If your code subclasses JPanel it will behave as a JPanel in the form editor, if it subclasses a JButton it would behave like a JButton and so on... This also removes the need for any quick hacks in the “customise code” part of the editor.
So to sum up: (1) compile your code, (2) then add the ZoneGrafica using the “Add Java Bean” function. You will need to know its fully qualified classname (e.g. com.foo.ZonaGrafica) for that.

Related

illegal forward reference netbeans swing

I am building a GUI with swing in netbeans. In Designing GUI,netbeans instantiates all the variables at the end of the program which cannot be manipulated.Now I want to get the Jtextfield data and put it in a String object. Suppose netbeans created my JTextField variable as jTextField1 and if I do
String name=jTextField1.getText() at the beginning
it shows the error of illegal forward reference and if I try to define this at the end of the program(after all netbeans' declarations)it throws millions of exceptions.
So what should I do to declare this string object and retrieve the value of gettext() in a variable?
EDITED:
//The code
import javax.swing.JOptionPane;
public class LoginInternalFrame extends javax.swing.JInternalFrame
{
public LoginInternalFrame()
{
initComponents();
}
public int check()
{
if(jTextField1.getText().equals(""))
{
return 0;
}
if(jPasswordField1.getText().equals(""))
{
return 0;
}
return 1;
}
//HERE I AM TRYING TO DECLARE ********************
String user = jTextField1.getText();
//THIS IS SHOWING ILLEGAL FORWARD REFERENCE BECAUSE jTextField IS DECLARED AT THE END OF THE CODE WHICH IS UNMODIFIABLE IN THE IDE
//HERE STARTS NETBEANS' GENERATED CODE
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jPasswordField1 = new javax.swing.JPasswordField();
jButton1 = new javax.swing.JButton();
setClosable(true);
setIconifiable(true);
setMaximizable(true);
setResizable(true);
jLabel1.setFont(new java.awt.Font("Tekton Pro", 0, 18)); // NOI18N
jLabel1.setText("Username");
jLabel2.setFont(new java.awt.Font("Tekton Pro Ext", 0, 18)); // NOI18N
jLabel2.setText("Password");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jButton1.setFont(new java.awt.Font("Tarzan", 1, 18)); // NOI18N
jButton1.setText("Login");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(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(213, 213, 213)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(127, 127, 127)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 245, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(351, 351, 351))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(93, 93, 93)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(49, 49, 49)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(84, 84, 84)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(145, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
//NETBEANS' GENERATED CODE ENDS.
//THE ACTIOINPERFORMED METHODS
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(check()==0)
{
JOptionPane.showMessageDialog(this, "All Fields are Required...","Error",JOptionPane.ERROR_MESSAGE);
return;
}
WelcomeUser ww=new WelcomeUser();
ww.setVisible(true);
this.setVisible(false);
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
//THESE ARE THE UNMODIFIABLE DECLARATIONS IN THE END.NOW WHEN I TRY DECLARE STRING HERE ,THE IDE SHOWS A LOT OF EXCEPTIONS.
}
and I am not able to get the textfield's text in the string variable.
My guess is that you have the name String declared in the initialization portion of the code, outside of any constructor or method, and so before your jtf JTextField has been declared. If so, the solution is, yeah, OK, declare name in this region, but don't try to initialize it with the JTextField's text yet.
Edit: yep, I'm right -- you're declaring the user variable outside of any constructor or method, and that is fine, but you're also trying to initialize it there with the JTextField jTextField1's text as well, and that doesn't make sense. Not only isn't the text field variable yet declared, but even if it were declared, it's not even constructed yet. And even if it were constructed, it wouldn't hold any useful text as the user hasn't had a chance to fill it with text yet.
Solution: initialize your String with an empty String, "", and then in some sort of event, perhaps an ActionListener that the user calls after he has filled the text field with text, give your name variable the text held by your JTextField.
Edit 2: Thanks for improving your question!
Edit 3
You state in comment:
But there is still one conceptual problem that say when I press "enter" button on my gui page(without writing anything in the text field),the check function gets invoked(in my program)and there in the if statement getText works?(So there is STILL nothing written in the textfield and the jTextField1 has also not been declared yet!)
Actually yes, it has now been declared, and now may have text within it (if the user presses enter after entering text). It's not so much important where you access the variable geographically in the code, unless you're within the same scope level, but rather where you access it logically. Since you're accessing it from a non-static method, and since your JTextField variable is declared in the declaration part of your class, the compiler knows that it has been declared already.
Edit 4
A key concept is to understand what objects can and cannot do, and that Strings are immutable -- cannot be changed. Note that if your initial declaration were allowed, it would still not be helpful, since when the JTextField's text changed, your name variable would not. The only way for it to change would be for you to assign a new String (likely the new one in the JTextField) when needed, when an event occurs. There's no magic in Java.
Also as an aside regarding your check() method, since it returns a binary result, why not make it return boolean. Also, you should not call getText() on a JPasswordField as that greatly reduces the security of your program as it exposes the password text. I'd do something like:
//!! make this boolean
public boolean check() {
if (jTextField1.getText().trim().isEmpty()) {
return false;
}
if (jPasswordField1.getPassword().length == 0) {
return false;
}
return true;
}
and then call it like so:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (check()) {
// ....

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.

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.

Updating JTable

I have little confusion. I am trying to update JTable, but the updates are not coming up. This is my present code:
private void addTable(){
table = new JTable();// the table for 'Benchmark' tab
table.setShowVerticalLines(false);
table.setBorder(null);
data = new Object[][] {
{"Key", ""},//result[0]
{"Precision", ""},//result[2]+" %"
{"Cipher", ""},//result[4]
{"Language", ""},
{"Performance", ""},//result[3]
};
String [] header = new String[] {"Subject of Interest", "Output"};
model = new DefaultTableModel(data, header);
table.setModel(model);
table.getColumnModel().getColumn(0).setPreferredWidth(136);
table.getColumnModel().getColumn(1).setPreferredWidth(550);
GroupLayout gl_panelBenchmark = new GroupLayout(panelBenchmark);
gl_panelBenchmark.setHorizontalGroup(
gl_panelBenchmark.createParallelGroup(Alignment.TRAILING)
.addComponent(textInfoCrypto, GroupLayout.DEFAULT_SIZE, 759, Short.MAX_VALUE)
.addGroup(gl_panelBenchmark.createSequentialGroup()
.addGap(10)
.addComponent(textPane, GroupLayout.DEFAULT_SIZE, 739, Short.MAX_VALUE)
.addGap(10))
.addGroup(Alignment.LEADING, gl_panelBenchmark.createSequentialGroup()
.addContainerGap()
.addComponent(table, GroupLayout.DEFAULT_SIZE, 739, Short.MAX_VALUE)
.addContainerGap())
);
gl_panelBenchmark.setVerticalGroup(
gl_panelBenchmark.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panelBenchmark.createSequentialGroup()
.addContainerGap()
.addComponent(textInfoCrypto)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(textPane, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(table, GroupLayout.PREFERRED_SIZE, 79, Short.MAX_VALUE)
.addContainerGap())
);
panelBenchmark.setLayout(gl_panelBenchmark);
}
And this is how I am trying to update, at this stage, a single row. The below code has been invoked from another method:
data[0][0]= result[0];
model.fireTableCellUpdated(0, 0);
At this stage I can see only the table frames including row names, but no data. Any help, please?
data is only local data not contained in the table model. You need to use:
tableModel.setValue(result[0], 0, 0);
all fireXxxXxx event has DefaultTableModel implemented and correctly
JTable in this from and based on DefaultTableModel haven't any issue with update ModelToView or ViewToModel, there no restriction,
have to edit your questin with SSCCE
before that read JTable tutorial
especially JTable and TableModel

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