简体   繁体   English

如何在Java中设置背景色

[英]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. 大家好,我实际上是Java编程的新手。我可以在哪里放置背景色代码。因为在main方法中放置带有黄色的jpanel时,在jframe中设置背景色是可行的,但是jlabel,jtextfield和jbutton现在不见了..一切都只是黄色。

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); 更改jPanel Backgroundcolor: jPanel.setBackground(Color.YELLOW); And then you need to set jPanel.setOpaque(false); 然后您需要设置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. 尝试使用netbeans开发。 It has all the features to decorate using the IDE itself. 它具有使用IDE本身进行装饰的所有功能。 Then you can see the code also in the source. 然后,您也可以在源代码中看到代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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