在GUI上更改颜色

时间:2017-09-17 16:45:01

标签: java swing user-interface

public ATMgui1() 
{
    setTitle("ATM Transactions");
    setSize(WIDTH, HEIGHT);
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    JPanel contentPane = new JPanel();

    contentPane.setBackground(Color.PINK);
    setContentPane(contentPane);
    contentPane.setOpaque(false);

    JLabel pinLabel = new JLabel("Enter your Pin:");
    pinLabel.setOpaque(false);
    pinTextField = new JTextField();
    JButton pinButton = new JButton( "EnterPin OK");
    pinButton.setOpaque(false);

    JLabel pinChangeLabel = new JLabel("Enter your new Pin:");
    JTextField pinChangeTextField = new JTextField();
    JButton pinChangeButton = new JButton( "Change Pin");

    JButton exitButton = new JButton("EXIT");
    exitButton.addActionListener(e -> this.dispose());

    pinButton.addActionListener(this);

    JPanel pinPanel = new JPanel();
    pinPanel.setLayout(new GridLayout(3, 3));
    pinPanel.add(pinLabel);
    pinPanel.add(pinTextField);
    pinPanel.add(pinButton);
    pinPanel.add(pinChangeLabel);
    pinPanel.add(pinChangeTextField);
    pinPanel.add(pinChangeButton);

    pinPanel.add(exitButton);

    contentPane.add(pinPanel, BorderLayout.CENTER);

我尝试改变背景,但它并没有完全改变,代码有点遍布整个地方,我认为它只是在一个部分,实际上我正在努力。

1 个答案:

答案 0 :(得分:3)

您所看到的内容:

enter image description here

保存组件,JTextFields,标签和按钮的JPanel应该是非透明的。在其上调用SCHED_OTHER,您应该看到它下方的颜色。

例如:

.setOpaque(false)

让你的pinPanel不透明。 contentPane,您设置为粉红色的组件应保持不透明:

import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class PinkBackground {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JPanel panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
            panel.add(new JTextField(10));
            panel.add(Box.createVerticalStrut(15));
            panel.add(new JTextField(10));
            panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

            // panel.setOpaque(false);  // ******* uncomment this! **********

            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setBackground(Color.PINK);
            frame.add(panel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}