使用 Java Graphics,我尝试绘制一个简单的矩形。
因为Applet
它运行良好,但是当我用它在 a 上显示时JFrame
,矩形即将出现,但有一些不寻常的背景
这是编码:
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);
}
}
然后我尝试JTextArea
使用这两个类,但在这种情况下,矩形根本没有显示。
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);
}
}
和 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);
}
}
任何人都可以帮我在JFrame,
JPanel or
JTextarea 等任何摆动容器上显示图形组件吗?