Today while coding in java, I ran into two problems.
1. My controls are dynamically generated during runtime. i.e. I have a JTextPane (txtPane) and JButton (btnGenerateRandomNum). Say for example, when btnComment is clicked, I want to paste a randomly generated number into that particulat txtPane. (there are like 20 txtPane each with its own JButton). The question is, on receiving an event from JButton how do I actually go back to the correct txtPane and display the generated random number?
a. first of all you need to create a public list of Jpanels generated
private ArrayList panelList = new ArrayList();
b. add actionCommand with a counter, counter will serve as a unique identifier to the button generated by the java codes. Add this button to the panel and store the panel into the list.
btn.setActionCommand("annotate"+counter);
panel.add(btn);
panelList.add(panel);
c. under actionPerformed method, check that the command received starts with annotate, if it starts, obtain the button ID, based on that, we can obtain the panelList by index. Cast that into the control type you want, in this case, JTextPane, we specify that we want the first component in the JPanel by specifying the index as zero.
if (command.substring(0,8).equals("annotate")) {
int buttonID = Integer.parseInt(command.substring(8))
JPanel tmpPanel = (JPanel) panelList.get(buttonID);
JTextPane tmpArea = (JTextPane) tmpPanel.getComponent(0);
tmpArea.setText= "Yes Success!";
}
The three steps above, allowed us to very simply access controls that were dynamically generated by storing it in an arrayList and getting it back, setting values to it.
[edited, 23rd september]
2. I placed these generated controls into a panel then into a container (with scrollpane). I set the container layout to be BoxLayout. So whenever i click the button "new", a new Panel is inserted into the bottom of the container. This function works perfectly. But it dynamically resizes, i.e. since the height of the container is 500, by pushing the button, it will show 2 panels in correct sizes, by the time i reach the 3rd panel, the panels are resized automatically smaller. (it is trying to fit the size of the container)The question is how do i actually do something like this so that the panel don't resize itself? I tried flowlayout but it does not work correctly (the panel does not appear). I am not sure if there are any layout that I didn't know that works how i need it to - basically to display things from top to bottom (vertically) and don't resize it. Just like how a normal row is added in a table using PHP.
verContainer.setLayout(new BoxLayout(verContainer, BoxLayout.Y_AXIS));
verContainer.add("panel" + counter, inputPanel);
verContainer.setPreferredSize(new Dimension(500,200* counter));
Basically, to prevent dynamic resizing due to the container size, I increase the container size at the same time so that the box layout works perfectly without resizing.
No comments:
Post a Comment