I am having issues with connecting components within Swing in a way where they would interact or exert a flow of action. My plan is to disable/enable a JTextPane when a button is pushed, and then input numbers so that the program can start the computation. So far here is where I am stuck at:
private JPanel contentPane;
protected JTextPane txtpnA;
protected JTextPane txtpnB;
protected JTextPane txtpnC;
/* Button 'a' **/
JButton btnA = new JButton("a");
btnA.setBackground(Color.YELLOW);
btnA.setBounds(47, 54, 89, 23);
btnA.setActionCommand("a");
btnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
} {
}
});
contentPane.add(btnA);
/* TextPane 'a' **/
txtpnA = new JTextPane();
txtpnA.setBounds(47, 88, 89, 20);
contentPane.add(txtpnA);
txtpnA.setBorder(BorderFactory.createLineBorder(Color.black));
And here is the method:
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if(command.equals("a"))
{
txtpnA.setEnabled(false);
} else if(command.equals("b"))
{
txtpnB.setEnabled(false);
} else if(command.equals("c"))
{
txtpnC.setEnabled(false);
}
}
}
I am having hard time to find articles regarding communication between JComponents. If you could also suggest a verbose source, it'd be much appreciated.
I would suggest you to create a new class that can handle your request for a specific component and don't use anonymouse event handler:
public class ButtonHandler extends AbstractAction {
private JComponent componentToDisable;
public ButtonHandler(JComponent comp, String text) {
super(text);
componentToDisable = comp;
}
public void actionPerformed(ActionEvent event) {
componentToDisable.setEnabled(false);
}
}
How to use it:
/* TextPane 'a' **/
txtpnA = new JTextPane();
txtpnA.setBounds(47, 88, 89, 20);
contentPane.add(txtpnA);
txtpnA.setBorder(BorderFactory.createLineBorder(Color.black));
JButton btnA = new JButton(new ButtonHandler(textpnA, "a"));
btnA.setBackground(Color.YELLOW);
btnA.setBounds(47, 54, 89, 23);
contentPane.add(btnA);
The same procedure for other buttons.
JButton btnB = new JButton(new ButtonHandler(textpnB, "b"));
JButton btnC = new JButton(new ButtonHandler(textpnC, "c"));
And last but not least. As it already mentioned by Andrew Thompson:
Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.