Java框架颜色未改变。

huangapple go评论75阅读模式
英文:

java frame not changing colour

问题

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

public class UserLoginPage implements ActionListener {
    // 将所有的JLabel、Frames和buttons等放在这里
    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");

    // 用于成功登录的标签
    JLabel success = new JLabel();

    // 默认构造函数来添加框架和面板等
    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);

        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");
        }
    }
}
英文:

I am unable to change the colour of my frame in Java code below. I know the code to change it would be frame.getContentPane().setBackground(Color.gray); However, this is not working for me, I am not sure what is the reason behind this, but if you are able to solve the problem do let me know, thank you.

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");
}
}
}

答案1

得分: 6

你正在向你的 JFrame 添加一个 JPanel,由于 JFrame 的 contentPane 使用了 BorderLayout,这个 JPanel(是不透明的)将完全覆盖 contentPane,阻止了 contentPane 背景的可视化。

解决方案:

  • 要么通过 panel.setOpaque(false); 使面板变为非透明,这样它的容器的颜色或图像将会显示出来
  • 要么保持默认的不透明度,但是为它和 contentPane 都设置所需的背景颜色。

另一个无关的问题在这里:

panel.setLayout(null)

出于许多原因,你真的不应该这样做,其中包括这将使你的 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);
    }
}

@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();
            }
        }
    }
}
英文:

You're adding panel, a JPanel to your JFrame, and since JFrame's contentPane uses a BorderLayout, this JPanel (which is opaque), will completely cover the contentPane, preventing visualization of the contentPane's background.

Solution:

  • Either make the panel not-opaque via panel.setOpaque(false); so that now its container's colors or images will show through
  • or leave it default opaque give it and not the contentPane the background color of choice.

Unrelated issue is here:

panel.setLayout(null)

You really don't want to be doing this for many reasons, including because this will make your GUI work well / look nice on only one platform. It also makes it very hard to upgrade and enhance the GUI later.


For example, and incorporating some of Andrew Thompson's suggestions, here is an example login GUI that is geared towards creating a JPanel, one that in this example is placed into a modal JDialog (similar to a JOptionPane but with more flexibility) and displayed. The code uses GridBagLayout along with GridBagConstraints when adding components to place them where I want them to be in a pleasing way that works on all platforms, and that allows ease and flexibility should I want to add more components:

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);
}
}

<!-- -->

@SuppressWarnings(&quot;serial&quot;)
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(&quot;User Name: &quot; + userName);
System.out.println(&quot;Password:  &quot; + new String(password));
Component source = (Component) e.getSource();
if (source != null) {
Window window = SwingUtilities.getWindowAncestor(source);
if (window != null) {
window.dispose();
}
}
}
}

huangapple
  • 本文由 发表于 2020年7月26日 03:31:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63092685.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定