开发者

GridLayout Panel Button Text Update at runtime

I am working on GUI using swing. I have a main class from where i am loading two separate panels initially. My First Panel has a textField and a button & second panel which is a Grid Layout embedded in panel, like 9 buttons numbered as A1,A2,A3,...A9. So as i said both these are loaded from my main class initially.

Now after executing, as i see both my separate panels.Now from Panel 1(which has Text Field and button) i put some text there e.g number A1. What i want is the color of button on second panel should change.

What i did i added an ActionListiner to my button on firstPanel and created new instance of second Panel. But this way Panel 2 duplicates. So as i keep on adding n开发者_Go百科umber in textField i see new panel. How can i just update the existing second panel button color at run time?


I suppose you have something like

JPanel panel2 = new JPanel(new GridLayout(3,3));
JButton[] buttons = new JButton[9];

// instantiate buttons and add them to grid panel
for (int i = 0; i < 9; ++i) {
  buttons[i] = new JButton("A"+(i+1));
  panel2.add(buttons[i]);
}

....

void actionPerformed(ActionEvent e) {
  String text = ((JTextField)e.getSource()).getText();

  //simplified, I assume input is always correct and in the form of "An" where n is the digit
  // convert the string to an index to reference the correct button in array
  int which = Integer.parseInt(text.substring(1,2));

  buttons[which].setBackground(Color.RED);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜