我试图显示日历,如果我点击右键我想要更改该按钮的颜色。其实我要进入弹出菜单,但我怎么知道先点击了哪个按钮?
panel1date.setLayout(new GridLayout(6,7));
for(int i=0; i<btnArr.length;i++){
btnArr[i] = new Button("");
btnArr[i].addMouseListener(new MemoHandler());
panel1date.add(btnArr[i]);
}
btnPrevMon.addActionListener(new BtnEventHandler());
btnNextMon.addActionListener(new BtnEventHandler());
void setDays(Calendar date){
int year = date.get(Calendar.YEAR);
int month = date.get(Calendar.MONTH);
lblYearMon.setText(year+"year+"+(month+1)+"month");
Calendar sDay = Calendar.getInstance();
sDay.set(year, month, 1);
sDay.add(Calendar.DATE, -sDay.get(Calendar.DAY_OF_WEEK)+1);
for(int i=0; i<btnArr.length; i++, sDay.add(Calendar.DATE, 1)){
int day = sDay.get(Calendar.DATE);
btnArr[i].setLabel(day+"");
if(sDay.get(Calendar.MONTH)!=month) {
btnArr[i].setBackground(Color.lightGray);
}
else {
btnArr[i].setBackground(Color.white);
}
}
}
class BtnEventHandler implements ActionListener{
public void actionPerformed(ActionEvent ae) {
String msg = tf1.getText();
Button src = (Button)ae.getSource();
if(src==btnPrevMon) {
curMon.add(Calendar.MONTH, -1);
}
else
if(src==btnNextMon) {
curMon.add(Calendar.MONTH, 1);
setDays(curMon);
repaint();
}
}
class EventHandler extends FocusAdapter implements ActionListener {
public void actionPerformed(ActionEvent ae) {
String msg = tf1.getText();
if("".equals(msg))
return;
if(dataOut!=null) {
try {
dataOut.writeUTF(nickname+">"+msg);
}
catch(IOException e) {
}
}
ta1.append("\r\n" + nickname +">"+ msg);
tf1.setText("");
}
}
class MemoHandler extends MouseAdapter implements MouseListener{
public void mouseClicked(MouseEvent e){
if (e.getButton() == MouseEvent.BUTTON1)
diarymemo = new DiaryButtonMemo(Client.server_ip, Client.server_port);
if (e.getButton() == MouseEvent.BUTTON3)
btnArr[].setBackground(Color.RED);
}
}
public static void main(String[] args) {
DiaryClient di = new DiaryClient();
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:1)
要更改按钮颜色,请使用:
Color background;
button.setBackground(background);
显示弹出菜单:
public class PopupMenu extends JPanel {
JPopupMenu popup;
public PopupMenu() {
popup = new JPopupMenu();
JMenuItem item;
popup.add(item = new JMenuItem("Popup"));
item.addActionListener(new new ActionListener() {
public void actionPerformed(ActionEvent event) {
// Action performed
System.out.println("I know which popup menu item ["
+ event.getActionCommand() +
"] was pressed.");
});
});
addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
doPopup(e);
}
public void mouseClicked(MouseEvent e) {
doPopup(e);
}
public void mouseReleased(MouseEvent e) {
doPopup(e);
}
private void doPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.show(PopupMenu.this, e.getX(), e.getY());
}
}
});
}
}