【发布时间】:2013-12-06 14:20:24
【问题描述】:
我有一个正在进行的项目。我试图在按下按钮时将标志布局从水平更改为垂直。我在if "Bulgaria" 语句下添加了一行代码来改变网格布局,但是它不起作用。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Flags extends JFrame implements ActionListener {
Container pane;
JPanel display,displayCenter,displayBottom,displayTop,buttonArea;
JButton Flag1,Flag2,Flag3,Flag4,Flag5,Flag6;
public Flags () {
setSize(600, 500);
setTitle("Flags");
setLocation(150, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pane = getContentPane();
pane.setLayout(new BorderLayout());
display = new JPanel(new GridLayout(3,0));
displayTop=new JPanel();
display.add(displayTop);
displayCenter=new JPanel();
display.add(displayCenter);
displayBottom=new JPanel();
display.add(displayBottom);
pane.add(display, BorderLayout.CENTER);
Flag1 = new JButton ("Argentina");
Flag1.addActionListener(this);
Flag2 = new JButton ("Armenia");
Flag2.addActionListener(this);
Flag3 = new JButton ("Austria");
Flag3.addActionListener(this);
Flag4 = new JButton ("Azerbaijan");
Flag4.addActionListener(this);
Flag5 = new JButton ("Bolivia");
Flag5.addActionListener(this);
Flag6 = new JButton ("Bulgaria");
Flag6.addActionListener(this);
buttonArea = new JPanel();
buttonArea.setLayout(new FlowLayout());
buttonArea.setBackground(Color.BLACK);
buttonArea.add(Flag1);
buttonArea.add(Flag2);
buttonArea.add(Flag3);
buttonArea.add(Flag4);
buttonArea.add(Flag5);
buttonArea.add(Flag6);
pane.add(buttonArea, BorderLayout.SOUTH);
}
public void actionPerformed (ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Argentina")){
displayTop.setBackground(new Color(155,242,242));
displayCenter.setBackground(Color.WHITE);
displayBottom.setBackground(new Color(155,242,242));
}
if (command.equals("Armenia")){
displayTop.setBackground(Color.RED);
displayCenter.setBackground(Color.BLUE);
displayBottom.setBackground(new Color(232,152,5));
}
if (command.equals("Austria")){
displayTop.setBackground(Color.RED);
displayCenter.setBackground(Color.WHITE);
displayBottom.setBackground(Color.RED);
}
if (command.equals("Azerbaijan")){
displayTop.setBackground(Color.BLUE);
displayCenter.setBackground(new Color(232,84,5));
displayBottom.setBackground(new Color(18,179,18));
}
if (command.equals("Bolivia")){
displayTop.setBackground(Color.RED);
displayCenter.setBackground(Color.YELLOW);
displayBottom.setBackground(new Color(21,179,21));
}
if (command.equals("Bulgaria")){
display = new JPanel(new GridLayout(0,3));
displayTop.setBackground(Color.WHITE);
displayCenter.setBackground(new Color(19,138,19));
displayBottom.setBackground(Color.RED);
}
}
public static void main (String [] args) {
Flags demo = new Flags();
demo.setVisible(true);
}
}
【问题讨论】:
标签: java swing user-interface actionlistener grid-layout