我制作了一个简单的测试小程序,它有一个红色背景和几个按钮。当我运行applet(它在http://nuevawave.org/sandbox/JavaGallery/GUIApplet.html时)按钮显示,但红色不显示。当我点击小程序时,有时背景的一部分会闪烁红色。有谁知道可能是什么问题?
以下是applet代码:
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JApplet.*;
public class GUIApplet extends javax.swing.JApplet {
/** Initializes the applet GUIApplet */
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void paint(Graphics g) {
super.paint(g);
}
/** This method is called from within the init() method 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() {
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setBackground(new java.awt.Color(255, 0, 0));
setMaximumSize(new java.awt.Dimension(250, 300));
setPreferredSize(new java.awt.Dimension(250, 300));
setSize(new java.awt.Dimension(250, 300));
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTextField1.setText("jTextField1");
getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 170, -1, -1));
jButton1.setText("jButton1");
getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(17, 90, -1, -1));
jButton2.setText("jButton2");
getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 90, -1, -1));
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
答案 0 :(得分:6)
您需要设置JApplet的contentPane的背景,而不是JApplet本身,因为它是实际保存组件并正在显示的contentPane。在您的init方法中调用getContentPane().setBackground(...);
,而不是裸setBackground(...)
次调用。