有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java颜色背景不起作用

我试图在swing中更改背景色,但它不起作用

我试过this.getContentPane().setBackground(Color.YELLOW);,也试过frame.getContentPane().setBackground(Color.YELLOW);

以下是完整的代码:

public class RoomGUI extends JFrame implements ActionListener{

    private static final long serialVersionUID = 1L;
    // will first hold "Username:", later on "Enter message"
    private JLabel label;
    // to hold the Username and later on the messages
    private JTextField tf;
    // to hold the server address an the port number
    private JTextField tfServer, tfPort;
    // to Logout and get the list of the users
    private JButton logout,send, whoIsIn;
    // for the chat room
    private JTextArea ta;
    // if it is for connection
    private boolean connected;
    // the Client object
    private Client client;
    // the default port number
    private int defaultPort;
    private String defaultHost;

    private LoginGUI sg;
    private JList<String> whoIsInList,skills;
    private DefaultListModel<String> listModel,listModel2;

    private JFrame frame;
    private JButton btnStartChat;
    private JScrollPane scrollPane1,scrollPane2;




    /**
     * Create the application.
     */

    RoomGUI(String host, int port, String name,DefaultListModel<String> skillsList) {

        super("Chat Client");

        listModel2 = new DefaultListModel<>();
        //listModel2.addElement("USA"); 
        for(int i=0;i<skillsList.getSize();i++){
            listModel2.addElement(skillsList.getElementAt(i));
        }
        skills = new JList<>(listModel2);



        //loop on skillslist
        //      for(int i=0;i<skillsList.getSize();i++){
        //      System.out.println(skillsList.getElementAt(i));
        //      
        //      }

        defaultPort = port;
        defaultHost = host;


        //System.out.println(skillsList.getModel().getSize());
        frame = new JFrame();
        frame.setBounds(100, 100, 767, 708);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        ta = new JTextArea("Hi " +name+ "!! Welcome to the Chat room, Click \"Start chat\" to begin \n");
        ta.setBounds(190, 53, 525, 514);//525       



        scrollPane2 = new JScrollPane();
        scrollPane2.setBounds(190, 53, 525, 514);
        frame.getContentPane().add(scrollPane2);
        scrollPane2.setViewportView(ta);



        tf = new JTextField(name);
        tf.setEditable(false);
        tf.setBounds(190, 574, 425, 44);    
        frame.getContentPane().add(tf);




        send = new JButton("Send");
        send.setBounds(627, 574, 88, 44);
        send.addActionListener(this);
        frame.getContentPane().add(send);
        send.setEnabled(false);
        //btnNewButton.setEnabled(false);// you have to write something before being able to click "send"

        JLabel lblWhosOnline = new JLabel("Who's online:");
        lblWhosOnline.setFont(new Font("Tahoma", Font.BOLD, 17));
        lblWhosOnline.setBounds(36, 13, 126, 38);
        frame.getContentPane().add(lblWhosOnline);


        tfPort = new JTextField(" "+port);
        tfPort.setBounds(599, 13, 116, 22);
        frame.getContentPane().add(tfPort);
        tfPort.setColumns(10);

        JLabel lblPortNumber = new JLabel("Port number:");
        lblPortNumber.setBounds(503, 13, 92, 22);
        frame.getContentPane().add(lblPortNumber);

        tfServer = new JTextField(" "+host);
        tfServer.setBounds(331, 13, 116, 22);
        frame.getContentPane().add(tfServer);
        tfServer.setColumns(10);

        JLabel lblHost = new JLabel("Server Address:");
        lblHost.setBounds(226, 13, 106, 22);
        frame.getContentPane().add(lblHost);

        logout = new JButton("logout");
        logout.setBounds(28, 626, 97, 27);
        logout.addActionListener(this);
        frame.getContentPane().add(logout);

        btnStartChat = new JButton("Start chat");
        btnStartChat.setBounds(140, 626, 97, 27);
        btnStartChat.addActionListener(this);
        frame.getContentPane().add(btnStartChat);



        //create the model and add elements 
        listModel = new DefaultListModel<>(); 
        //      listModel.addElement("USA"); 
        //      listModel.addElement("India"); 
        //      listModel.addElement("Vietnam"); 



        scrollPane1 = new JScrollPane();
        scrollPane1.setBounds(23, 53, 156, 565);
        frame.getContentPane().add(scrollPane1);


        whoIsIn = new JButton("Who is in");
        whoIsIn.addActionListener(this);
        whoIsIn.setBounds(252, 626, 97, 27);
        frame.getContentPane().add(whoIsIn);


        //create the list 
        whoIsInList = new JList<>(listModel);
        //frame.getContentPane().add(whoIsInList);
        whoIsInList.setBounds(12, 53, 366, 563);
        scrollPane1.setViewportView(whoIsInList);

        this.getContentPane().setBackground(Color.YELLOW);

        frame.setVisible(true);

    }
    // called by the Client to append text in the TextArea 
    void append(String str) {

        ta.append(str);
        ta.setCaretPosition(ta.getText().length() - 1);
    }

    // Added by me: called by the Client to append text in the Jlist 
    void append2(String str) {
        listModel2 = new DefaultListModel<>();
        System.out.println("appppppppppen222");
        String[] q={};
        try{
            //((DefaultListModel)whoIsInList.getModel()).clear();
            //whoIsInList.setListData(listModel2);


            //whoIsInList.setListData(q);
            listModel.addElement(str);

        }
        catch(Exception e){
            System.out.println(e);
        }

    }
    // called by the GUI is the connection failed
    // we reset our buttons, label, textfield
    void connectionFailed() {
        //login.setEnabled(true);
        logout.setEnabled(false);
        //whoIsIn.setEnabled(false);
        //label.setText("Enter your username below");
        tf.setText("Anonymous-tf");
        // reset port number and host name as a construction time
        tfPort.setText("" + defaultPort);
        tfServer.setText(defaultHost);
        // let the user change them
        tfServer.setEditable(false);
        tfPort.setEditable(false);
        // don't react to a <CR> after the username
        tf.removeActionListener(this);
        connected = false;
    }

    /*
     * Button or JTextField clicked
     */

    public void actionPerformed(ActionEvent e) {
        Object o = e.getSource();


        if(o == logout) {
            System.out.println("You logged out");
            frame.setVisible(false);
            JOptionPane.showMessageDialog(null,"Bye bye!");
            client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));    
            return;
        }

        if(o == btnStartChat) {
            // ok it is a connection request
            btnStartChat.setEnabled(false);
            tf.setEditable(true);
            send.setEnabled(true);
            String username = tf.getText().trim();
            // empty username ignore it
            if(username.length() == 0)
                return;
            // empty serverAddress ignore it
            String server = tfServer.getText().trim();
            if(server.length() == 0)
                return;
            // empty or invalid port numer, ignore it
            String portNumber = tfPort.getText().trim();
            if(portNumber.length() == 0)
                return;
            int port = 0;
            try {
                port = Integer.parseInt(portNumber);
            }
            catch(Exception en) {
                return;   // nothing I can do if port number is not valid
            }


            String[] s=new String[listModel2.getSize()];
            for(int i=0;i<listModel2.getSize();i++){
            s[i]=listModel2.getElementAt(i);

            }
            frame.getContentPane().setBackground(Color.YELLOW);

            // try creating a new Client with GUI
            /*client = new Client(server, port, username, this,s);*///<--------------------------return this line after
            // test if we can start the Client
            if(!client.start()) 
                return;
            tf.setText("");
            //label.setText("Enter your message below");
            connected = true;

            // disable login button
            //login.setEnabled(false);
            // enable the 2 buttons
            logout.setEnabled(true);
            //whoIsIn.setEnabled(true);
            // disable the Server and Port JTextField
            tfServer.setEditable(false);
            tfPort.setEditable(false);

            // Action listener for when the user enter a message
            tf.addActionListener(this);

        }

        if(o==send) {
            //System.out.println("Check if connected");
            // just have to send the message
            client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, tf.getText()));             
            tf.setText("");
            return;
        }

        // if it the who is in button
        if(o == whoIsIn) {
            System.out.println("Check whosin button");
            ((DefaultListModel)whoIsInList.getModel()).clear();
            client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, ""));               
            return;
        }


    }

    /**
     * Launch the application.
     */ 
    public static void main(String[] args) {

        DefaultListModel<String> skillsList = new DefaultListModel<>();;
        new ClientGUI("localhost",1500,"Some name",skillsList);

    }
}

共 (1) 个答案

  1. # 1 楼答案

    在main方法中,您正在调用ClientGui,但是您的类名是RoomGUI。另外,为什么要扩展Jframe并且还拥有一个私有的JFrame