Reputation: 490
I am studying how to programming in Java. Currently I am in the chapter of Swing. I am trying to draw a string in a frame with the next code.
Can someone tell me where is the mistake?
package paquete_swing;
import javax.swing.*;
import java.awt.*;
public class graficos {
public static void main(String[] args) {
MarcoConTexto primer_texto = new MarcoConTexto();
primer_texto.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MarcoConTexto extends JFrame {
public MarcoConTexto (){
setVisible(true);
//setBounds(400, 200, 600, 450);
setSize(600,450);
setLocation(400, 200);
setTitle("Primer Texto");
lamina milamina= new lamina();
add(milamina);
}
}
class lamina extends JPanel{
public void paintComponents(Graphics g) {
super.paintComponents(g);
g.drawString("Mi primer texto en una lamina de java",100 ,100 );
}
}
Upvotes: 0
Views: 319
Reputation: 51485
Sure, I'll point out the mistakes.
You must always start a Swing application with a call to the SwingUtilities invokeLater method. This ensures that the Swing components are created and updated on the Event Dispatch thread (EDT).
Class names start with a capital letter. This allows you and us to tell a class name from a method name or a variable name.
As others have said, the JFrame methods must be called in a certain order. I've rearranged your JFrame method calls.
You use Swing components. You don't extend Swing components unless you are overriding one of the component methods, like we do in the Lamina class. I used a JFrame.
The only place I specified a size is for the Lamina drawing JPanel. You use Swing layouts to place Swing components in a JFrame or a JPanel.
You overrode the paintComponents method instead of the paintComponent method. It's an easy mistake to make.
Here's the runnable code with the corrections.
package paquete_swing;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Graficos implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Graficos());
}
@Override
public void run() {
JFrame frame = new JFrame();
frame.setTitle("Primer Texto");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Lamina milamina = new Lamina();
frame.add(milamina);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public class Lamina extends JPanel {
private static final long serialVersionUID = 4553173187556864421L;
public Lamina() {
this.setPreferredSize(new Dimension(400, 200));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Mi primer texto en una lamina de java", 100, 100);
}
}
}
Upvotes: 4