java框架不改变颜色

Jac*_*ake -1 java swing intellij-idea

我无法在下面的 Java 代码中更改框架的颜色。我知道改变它的代码是 frame.getContentPane().setBackground(Color.gray); 但是,这对我不起作用,我不确定这背后的原因是什么,但是如果您能够解决问题,请告诉我,谢谢。

public class UserLoginPage implements ActionListener {
    //Put all JLabels,Frames and buttons here etc
    JPanel panel = new JPanel();
    JFrame frame = new JFrame();
    JLabel userLabel = new JLabel("Username");
    JLabel passwordLabel = new JLabel("Password");
    JTextField userText = new JTextField();
    JTextField passwordText = new JTextField();
    JButton loginButton = new JButton("Login");

    //Label for successful login
    JLabel success = new JLabel();

    //Default Constructor to add the frames and panels etc
    public UserLoginPage(){
        panel.setLayout(null);
        userLabel.setBounds(10,20,80,25);
        panel.add(userLabel);
        passwordLabel.setBounds(10,50,80,25);
        panel.add(passwordLabel);

        userText.setBounds(100,20,165,25);
        panel.add(userText);
        passwordText.setBounds(100,50,165,25);
        panel.add(passwordText);

        loginButton.setBounds(10,80,80,25);
        loginButton.addActionListener(this);
        panel.add(loginButton);

        success.setBounds(10,110,300,25);
        panel.add(success);
        //success.setText();

        frame.setSize(500,500);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.gray);
        frame.setVisible(true);
        frame.add(panel);

    }


    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new UserLoginPage();
            }
        });
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        String user = userText.getText();
        String password = passwordText.getText();
        System.out.println(user + ", " + password);

        if(user.equals("Jackson") && password.equals("1234")){
            JOptionPane.showMessageDialog(frame,"Login successful");
        }
        else{
            JOptionPane.showMessageDialog(frame,"Invalid password or username");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Don*_*ter 6

您正在向JPanelJFrame添加面板 a ,并且由于 JFrame 的 contentPane 使用 BorderLayout,因此此 JPanel(不透明)将完全覆盖 contentPane,从而阻止 contentPane 背景的可视化。

解决方案:

  • 要么使面板不透明,panel.setOpaque(false);以便现在其容器的颜色或图像将显示出来
  • 或者让它默认不透明,给它而不是 contentPane 选择的背景颜色。

无关的问题在这里:

panel.setLayout(null)
Run Code Online (Sandbox Code Playgroud)

出于多种原因,您确实不想这样做,包括因为这将使您的 GUI 运行良好/仅在一个平台上看起来不错。这也使得以后升级和增强 GUI变得非常困难。


例如,并结合了 Andrew Thompson 的一些建议,这里有一个示例登录 GUI,它旨在创建一个 JPanel,在这个示例中,它被放置到一个模态 JDialog(类似于 JOptionPane,但具有更大的灵活性)并显示。在添加组件时,代码使用 GridBagLayout 和 GridBagConstraints 将它们放置在我希望它们在所有平台上工作的令人愉悦的位置,并且如果我想添加更多组件,则可以轻松和灵活:

import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class UserLoginPanel extends JPanel {
    private static final Color BACKGROUND = new Color(200, 200, 200);
    private JTextField userText = new JTextField(15);
    private JPasswordField passwordText = new JPasswordField(15);
    LoginAction loginAction = new LoginAction(this, "Login", KeyEvent.VK_L);
    JButton loginButton = new JButton(loginAction);

    public UserLoginPanel() {
        super(new GridBagLayout());
        setBackground(BACKGROUND);
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0; 
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        int insetGap = 4;
        gbc.insets = new Insets(insetGap, insetGap, insetGap, insetGap);
        
        add(new JLabel("User Name:"), gbc);
        
        gbc.gridx = 1;
        add(userText, gbc);
        
        gbc.gridx = 0;
        gbc.gridy = 1;
        add(new JLabel("Password"), gbc);
        
        gbc.gridx = 1;
        add(passwordText, gbc);
        
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        add(loginButton, gbc);
        
        insetGap = 8;
        setBorder(BorderFactory.createEmptyBorder(insetGap, insetGap, insetGap, insetGap));
    }
    
    public String getUserName() {
        return userText.getText();
    }
    
    public char[] getPassword() {
        return passwordText.getPassword();
    }
    
    public static void main(String[] args) {
        UserLoginPanel loginPanel = new UserLoginPanel();
        JDialog dialog = new JDialog(null, "User Login", ModalityType.APPLICATION_MODAL);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.add(loginPanel);
        dialog.pack();
        dialog.setLocationByPlatform(true);
        dialog.setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)
@SuppressWarnings("serial")
class LoginAction extends AbstractAction {
    private UserLoginPanel loginPanel;
    
    public LoginAction(UserLoginPanel loginPanel, String name, int mnemonic) {
        super(name);
        putValue(MNEMONIC_KEY, KeyEvent.VK_L);
        this.loginPanel = loginPanel;
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        String userName = loginPanel.getUserName();
        char[] password = loginPanel.getPassword();
        
        System.out.println("User Name: " + userName);
        System.out.println("Password:  " + new String(password));
        
        Component source = (Component) e.getSource();
        if (source != null) {
            Window window = SwingUtilities.getWindowAncestor(source);
            if (window != null) {
                window.dispose();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)