I have made a simple test applet that has a red background and a few buttons. When I run the applet (its at http://nuevawave.org/sandbox/JavaGallery/GUIApplet.html) the buttons show up, but the red doesn't. When I click the applet, sometimes part of the background flashes red. Does anyone know what might be the problem?
Here is the applet code:
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() 开发者_JS百科{
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
}
You need to set the background of the JApplet's contentPane, not the JApplet itself since it is the contentPane that actually holds the components and that is being displayed. Call getContentPane().setBackground(...);
in your init method instead of the naked setBackground(...)
call.
精彩评论