I have an array of button that displays images after image query. Now I am trying to add a checkbox under each button so user can check if that's a relevant image. I was going to have an array of Jpanel where each Jpanel consist of one button and checkbox but I don't know how to incorporate all the components in my code.This is what I have so far:
resultPanel = new JPanel[10];
resultPanel[10].add(relevantFB);
resultPanel[10].add(button);
for (int i = 1; i < 101; i++) {
button[i] = new JButton(newIcon);
relevantFB[i] = new JCheckBox();
relevantFB[i].setText("Relevant Image" + i);
panelBottom1.add(button[i]);
button[i].addActionListener(new IconButtonHandler(i, newIcon));
relevantFB[i].addActionListener(new IconCheckboxHandler(i, newIcon));
buttonOrder[i] = i;
checkboxOrder[i]=i;
}
For that you mustn't create JPanel for each pair(checkbox+button). You must create one Panel, and place components with help of layout manager. In is work for LayoutManager .
You can use GridBagLayout for that purposes. In next example I create 5 buttons and 5 checkboxes under buttons :
public class Example extends JFrame {
public Example() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
JButton btns[] = new JButton[5];
JCheckBox chboxes[] = new JCheckBox[5];
c.gridx = 0;
for(int i = 0;i<btns.length;i++){
btns[i] = new JButton(""+i);
getContentPane().add(btns[i],c);
c.gridx++;
}
c.gridy = 1;
c.gridx = 0;
for(int i = 0;i<chboxes.length;i++){
chboxes[i] = new JCheckBox(""+i);
getContentPane().add(chboxes[i],c);
c.gridx++;
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String...strings ){
Example e = new Example();
}
}
Use a JPanel with a GridBagLayout. Put buttons on the first row an checkboxes beneath.
--Edit--
Here is some code. This is assuming you have n icons in an array icon
. Unlike you I've assumed the icons are numbered staring at 0.
JPanel resultPanel = new JPanel() ;
GridBagLayout gbl = new GridBagLayout() ;
resultPanel.setLayout( gbl );
GridBagConstraints constraints = new GridBagConstraints() ;
JButton[] button = new JButton[n] ; ;
for( int i = 0 ; i < n ; ++i ) {
button[i] = new JButton( new ImageIcon( "path"+(i+1)+".jpg" ) ); }
button[i].addActionListener(new IconButtonHandler(i+1, icon[i]));
constraints.gridx = i ;
constraints.gridy = 0 ;
resultPanel.Add( button[i], constraints ) ; }
JCheckBox[] relevantFB = new JCheckBox[n] ; ;
for( int i = 0 ; i < n ; ++i ) {
relevantFB[i] = new JCheckBox();
relevantFB[i].setText("Relevant Image" + (i+1));
relevantFB[i].addActionListener(new IconCheckboxHandler(i+1, icon[i]));
constraints.gridx = i ;
constraints.gridy = 1 ;
resultPanel.add( relevantFB[i], constraints ) ; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.