Using Java Graphics, I tried to draw a simple rectangle.
As Applet
it runs well but when I use it to show on a JFrame
, the rectangle is coming but with some unusual background
Here is coding:
package graphicsex;
import java.awt.Graphics;
public class Graphics2 extends javax.swing.JFrame {
public static void main(String[] args) {
Graphics2 inst = new Graphics2();
inst.setVisible(true);
}
public Graphics2() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
g.drawRect(10, 20, 30, 40);
}
}
Then I tried to use JTextArea
using these two classes but in this case the rectangle is not displaying at all.
GraphicsEx1.java:
package graphicsex;
import javax.swing.JTextArea;
import java.awt.Graphics;
public class GraphicsEx1 extends javax.swing.JFrame {
private JTextArea jTextArea1;
{
//Set Look & Feel
try {
javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
GraphicsEx1 inst = new GraphicsEx1();
inst.setVisible(true);
}
public GraphicsEx1() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
{
jTextArea1 = new JTextArea();
getContentPane().add(jTextArea1);
jTextArea1.setBounds(7, 7, 371, 245);
jTextArea1.setEnabled(false);
}
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
postInitGUI();
}
public void postInitGUI() {
DisplayItems dp = new DisplayItems();
jTextArea1 = dp;
dp.setVisible(true);
this.add(jTextArea1);
}
}
And DisplayItems.java:
package graphicsex;
import java.awt.Dimension;
import java.awt.Graphics;
public class DisplayItems extends javax.swing.JTextArea {
public DisplayItems() {
super();
initGUI();
}
private void initGUI() {
try {
setPreferredSize(new Dimension(400, 300));
} catch (Exception e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
g.drawRect(10, 20, 50, 100);
g.drawString("Kalai", 90, 150);
}
}
Can any one help me display graphics components on any swing containers like JFrame,
JPanelor
JTextarea` etc.