Java - 如何从另一个方法设置容器窗格颜色?

时间:2014-01-21 18:31:46

标签: java swing colors jpanel containers

我有一个Container窗格,我正在使用gridbaglayout。设置颜色我pane.setbackground但我想从另一个方法和动作处理方法做到这一点。 pane.setbackground不起作用。我该怎么办?感谢。

package mcve;

import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class mcve extends JPanel implements ActionListener{

final static  boolean shouldFill = true;
final static  boolean shouldWeightX = true;
final static   boolean RIGHT_TO_LEFT = false;
static JFrame frame;
static JButton color1, color2, exit;

public static void addComponentsToPane(Container pane) throws IOException {
    if(RIGHT_TO_LEFT){
        pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    }

    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    if (shouldFill){
        c.fill = GridBagConstraints.HORIZONTAL; 
    }


    // here i can do it.
    pane.setBackground(Color.black);

    color1 = new JButton("color1");
    c.fill = GridBagConstraints.HORIZONTAL; 
    c.gridx=0;
    c.gridy=0;
    color1.setActionCommand("color1");
    color1.addActionListener(new mcve());
    pane.add(color1, c);

    color2 = new JButton("color2");
    c.fill = GridBagConstraints.HORIZONTAL; 
    c.gridx=1;
    c.gridy=0;
    color2.setActionCommand("color2");
    color2.addActionListener(new mcve());
    pane.add(color2, c);

    exit = new JButton("Exit");
    c.fill = GridBagConstraints.HORIZONTAL; 
    c.gridx=1;
    c.gridy=0;
    exit.setActionCommand("exit");
    exit.addActionListener(new mcve());
    pane.add(exit, c);

}

public  void actionPerformed(ActionEvent e){

   if ("exit".equals(e.getActionCommand())){
       System.exit(0);
       }
   else if ("color1".equals(e.getActionCommand())){
      // I DON'T KNOW
       }
   else if ("color2".equals(e.getActionCommand())){
      // I DON'T KNOW
       }

}

private static void createAndShowGUI(){
 frame = new JFrame("MCVE");
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 try {
        addComponentsToPane(frame.getContentPane());
    } catch (IOException e) {
        e.printStackTrace();
    }
 frame.pack();
 frame.setResizable(false);
 frame.setVisible(true);
}

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            createAndShowGUI();
        }
    });

}

}

1 个答案:

答案 0 :(得分:3)

   else if ("color1".equals(e.getActionCommand())){
       frame.getContentPane().setBackground(Color.BLACK);
       }
   else if ("color2".equals(e.getActionCommand())){
       frame.getContentPane().setBackground(Color.RED);
       }

..是一种方法。