简体   繁体   中英

How to Set background color in java

Hey guys I'm actually new in java programming.Where can I put the line of code for background color.Because when I put a jpanel with a color yellow in main method .The setting of background color in jframe works but the jlabel,jtextfield and jbutton are now missing..everything is just yellow.

package testpath;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

public class Testpath extends JFrame {

        JLabel label;
        JTextField tf;
        JButton button;

 public Testpath(){
       setLayout(new FlowLayout());

       label= new JLabel("Enter First Name");
       add(label);

       tf=new JTextField(10);
       add(tf);

       button=new JButton("Log In");
       add(button);

       event e=new event();
     button.addActionListener(e);
  }

 public class event implements ActionListener{
     public void actionPerformed(ActionEvent e){
         try{
             String word=tf.getText();
             FileWriter stream= new     FileWriter("C://Users//Keyboard//Desktop//file.txt");
             BufferedWriter out=new   BufferedWriter(stream);
             out.write(word);
         }catch (Exception ex){}
     }
 }


public static void main(String[] args) {
    Testpath gui=new Testpath();
    gui.setLocationRelativeTo(null);
    gui.setVisible(true);
    gui.setSize(400,250);
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  

}

}

Change the jPanel Backgroundcolor: jPanel.setBackground(Color.YELLOW); And then you need to set jPanel.setOpaque(false); because default it´s transparent. Other components doesn´t change their color if you just add this on a specific component.

Try to develop using netbeans. It has all the features to decorate using the IDE itself. Then you can see the code also in the source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM