Updating JTable - java

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

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()) {
// ....

Java Dynamic Layout

Im trying to do game in Java: Sudoku. I have some problems with layout.
It's in main class.
GroupLayout layout = new GroupLayout(getContentPane());
GroupLayout layout2 = new GroupLayout(getContentPane());
public void ustawLayout1()
{
this.getContentPane().setLayout(layout);
this.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(etykieta)
.addComponent(latwy)
.addComponent(sredni)
.addComponent(trudny)
.addComponent(start,0,0,450)
)
.addContainerGap(0, 0)
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addComponent(etykieta)
.addComponent(latwy)
.addComponent(sredni)
.addComponent(trudny)
.addContainerGap(0,Short.MAX_VALUE)
.addComponent(start)
);
}
public void ustawLayout2()
{
this.getContentPane().setLayout(layout2);
layout2.setAutoCreateGaps(true);
layout2.setAutoCreateContainerGaps(true);
layout2.setHorizontalGroup(
layout2.createSequentialGroup()
.addComponent(etykieta2)
.addComponent(zakoncz,0,0,450)
.addContainerGap(0, 0)
);
layout2.setVerticalGroup(
layout2.createSequentialGroup()
.addComponent(etykieta2)
.addContainerGap(0,Short.MAX_VALUE)
.addComponent(zakoncz)
);
}
It's not working and i don't know why.
I would like to do that when i press button "start" layout is changing to layout2.
If you are making a sudoku, try use GridLayout. Its more effective in this case.

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.

Massive space between components

Please have a look at the following code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GridLayoutTest2
{
private final JDialog msgDisplayer;
public GridLayoutTest2()
{
JLabel maleLabel = new JLabel("Male",JLabel.CENTER);
maleLabel.setBorder(BorderFactory.createEmptyBorder());
JLabel femaleLabel = new JLabel("Female",JLabel.CENTER);
femaleLabel.setBorder(BorderFactory.createEmptyBorder());
JLabel fmaleIcon = new JLabel();
fmaleIcon.setIcon(new ImageIcon(getClass().getResource("/images/TESTING-Image.gif")));
fmaleIcon.setBorder(BorderFactory.createEmptyBorder());
JLabel maleIcon = new JLabel();
maleIcon.setIcon(new ImageIcon(getClass().getResource("/images/TESTING-Image.gif")));
maleIcon.setBorder(BorderFactory.createEmptyBorder());
msgDisplayer = new JDialog();
msgDisplayer.setLayout(new GridLayout(4,1,1,1));
msgDisplayer.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
msgDisplayer.setTitle("Body Fat Percentage Classification");
msgDisplayer.add(femaleLabel);
msgDisplayer.add(fmaleIcon);
msgDisplayer.add(maleLabel);
msgDisplayer.add(maleIcon);
msgDisplayer.pack();
msgDisplayer.setVisible(true);
msgDisplayer.setLocationRelativeTo(null);
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new GridLayoutTest2();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This code contains a HUGE gap (space) between the labels and images screenshot attached). I do not want to have this space between labels and images. How can I eliminate it? I know I can go with the GridBagLayout to do it, but, is there any way in GridLayout? Please help!
GridLayout allocates an equals amount of space for all components based on the largest component in the container. If you don't wish to use a complex layout manager such as GridBagLayout, you could use BoxLayout, which uses the component's preferred sizes. A BoxLayout with Y_AXIS alignment would be suitable here.
Example
Thats not the gap space, its real size of JLabel's (maleLabel, fmaleLabel). Size of image determines size of parent JLabel and in GridLayout, all components will take size of largest component. Gap between components is 1 as you defined when setting layout. So solution of your problem lays in finding suitable layout manager.
Reimeus gave you an example of GridBagLayout and BoxLayout, and I would like to recommend you MiGLayout which is quite easy to use.
Its the Layout what matters!!
Here I have done a short EG with my GUI builder to show the adjustment of white space(or the size of JLabel):
More white space:
Code:
public class udyfash extends javax.swing.JFrame {
public udyfash() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images.jpg"))); // NOI18N
jLabel1.setText("yooo!!");
jLabel1.setBorder(javax.swing.BorderFactory.createCompoundBorder(null, javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(jLabel1)
.addContainerGap(39, Short.MAX_VALUE))
);
pack();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new udyfash().setVisible(true);
}
});
}
private javax.swing.JLabel jLabel1;
}
We say GridBag is complex,but use the Layout Manager you are ok with.

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

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.

Categories