JCheckboxes into a JScrollPane - java

Is there a way to add jcheckboxes into a jscrollpane?
I have an array of checkboxes and I want to add them into a Jscrollpane, which i will then add into a JOptionPane. So far I have this:
Object[] books = new Object[10000];
books[0] = "Choose books to purchase: ";
for(int l = 1;l<checkboxes.length;l++)
{
books[l] = checkboxes[l];
}
JList list = new JList(checkboxes);
//JTextPane test = new JTextPane();
//test.add(checkboxes[0]);
JScrollPane myScrollPane = new JScrollPane(list);
myScrollPane.setPreferredSize(new Dimension(250,250));
JOptionPane.showMessageDialog(null, "Choose the books you want to purchase below.\nPlease note that each book has a $5 shipping charge.\nThe books are formatted as Title - Author - Price", "Reminder",JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null,myScrollPane,"Book List",JOptionPane.OK_CANCEL_OPTION);
The output does not give me the checkboxes, just the pointer of the checkboxes i think.
As you can see, I've tried putting the checkboxes into a JList but failed.
Thanks a lot guys!

You can add the checkboxes to JPanel and that Jpanel can be shown in JDialog instead of JOptionPane.
And to add the Checkboxes to JPanel u can check this link
How to use JCheckbox array in JPanel array

Related

Names of my JTable columns not showing

I created a JFrame with Java Swing using a BorderLayout. Both east and west layout are fixed with some components, while BorderLayout at the center can change depending on what the user does. At the beginning there is a picture,
panelDinamycCenter = new JPanel ();
JScrollPane = new JScrollPane (panelDinamycCenter);
panelDinamycCenter.add (new JLabel ( "", new Imagelcon ( "......."), JLabel.CENTER));
jFrame.getContentPane (). add (JScrollPane, BorderLayout.CENTER);
Then a data entry screen, for which I used a GridBagLayout. In order to remove the picture and to insert the new screen I used this:
panelDinamycCenter.removeAll (),
then I add the various components. After
setVisible (true);
I have now created a JTable, to be included in panelDinamycCenter,
panelDinamycCenter.removeAll ();
String [] [] matrixValori = new String [arrayOggCreaJTableDeroghe.length] [arrayJTableNomeColumnDeroghe.length];
for (int i = 0; i <arrayOggCreaJTableDeroghe.length; i ++) {
matrixValori [i] = arrayOggCreaJTableDeroghe [i] .creaArrayString ();
}
DefaultTableModel model = new DefaultTableModel (matrixValori, arrayJTableNomeColumnDeroghe);
JTable JTable = new JTable (model);
jTable.setAutoResizeMode (JTable.AUTO_RESIZE_OFF);
panelDinamycCenter.add (JTable);
jFrame.setVisible (true);
All right, but I can not see the names of the columns. Why?
As shown in How to Use Tables: Adding a Table to a Container, "The scroll pane automatically places the table header at the top of the viewport." At a minimum, you need to replace the JScrollPane removed by removeAll():
JTable jTable = new JTable(model);
panelDinamycCenter.add(new JScrollPane(jTable));
Among alternatives, consider these:
Add the table header to PAGE_START, as suggested here.
Instead of removing and restoring, use CardLayout to switch between views.

Move checkbox from one panel to another in swing

I am trying to move all the selected checkboxes from panel1 into panel2 and also removing the checkboxes from panel1 after the transfer. I made two arraylist to hold the checkboxes
ArrayList<JCheckBox> todo_box = new ArrayList<JCheckBox>();
ArrayList<JCheckBox> inprogress_box = new ArrayList<JCheckBox>();
and when the user clicks on the button I have this,
for(JCheckBox cb : todo_box)
{
if(cb.isSelected() )
{
inprogress_box.add(cb);
jPanel2.add(cb);
jPanel2.revalidate();
cb.setVisible(false);
todo_box.remove(cb);
jPanel1.remove(cb);
jPanel1.revalidate();
}
}
Not sure if I'm on the right track since I'm getting an exception error inside netbean.

How to create JCheckBox for elements of an ArrayList

I have an array that fills in by the user. Then each element of this array will be a CheckBox. For example if the array has 6 elements, it must create 6 checkboxes.
This is how I tried to loop through the array and create the checkbox, but it only overwrite on one checkbox.
public static void main(String[] args) {
JFrame frame = new JFrame("Options");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
ArrayList<String> myArrayList = new ArrayList<String>();
myArrayList.add("checkbox 1");
myArrayList.add("checkbox 2");
myArrayList.add("checkbox 3");
myArrayList.add("checkbox 4");
myArrayList.add("checkbox 5");
for(String element : myArrayList){
JCheckBox box = new JCheckBox(element);
frame.add(box);
}
frame.setVisible(true);
}
It is important that I have the access to each single checkbox later, so I can specify for example if checkbox2 is selected, do this.
So is there any way to make these checkboxes dynamically according to the ArrayList's size?
Every time you add something new to the JFrame, it removes the thing that was previously in it.
You'll need to create a JPanel or some other container to hold the JCheckBoxes, and then put that inside the JFrame.
Also, you can keep track of the checkboxes in a List.
For instance:
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(BoxLayout.Y_AXIS, panel));
List<JCheckBox> checkboxes = new ArrayList<>();
for(String element : myArrayList) {
JCheckBox box = new JCheckBox(element);
checkboxes.add(box);
panel.add(box);
}
frame.add(panel);
The main problem is, you're adding all the check boxes to the same location on the frame.
A JFrame uses a BorderLayout by default. A BorderLayout allows a single component to be managed in each of its five available slots. Basically a BorderLayout will ignore all but the last component added to any of the slots
Instead, try changing the LayoutManager to something more useful, like FlowLayout or GridBagLayout depending on your needs
Take a look at Laying Out Components Within a Container for more details.
Depending on your needs, I might be tempered to fill the ArrayList with the JCheckBoxes instead of String or even a Map of some kind, to make it easier to link the text with the JCheckBox

Java iterate through JList which contains JPanel - JLabel

I am trying to iterate over a JList where each item contains:
JPanel - JLabel
Currently what i have is:
System.out.println("Reading all list items:");
System.out.println("-----------------------");
for (int i = 0; i < menuList.getModel().getSize(); i++) {
Object item = menuList.getModel().getElementAt(i);;
System.out.println("Item = " + item);
}
The output i get is:
Item =
javax.swing.JPanel[,0,0,0x0,invalid,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
Instead i want to access the text that is inside the JPanel.
How could this be done?
Edit:
This is how i add my JPanel to the JList
menuList = new JList(v);
v = new Vector <String> ();
menuList.setListData(v);
.....
// get our images
Icon pingImage = new javax.swing.ImageIcon(getClass().getResource("/resources/icnNew.png"));
// add the images to jlabels with text
JLabel pingLabel = new JLabel("Hi there", pingImage, JLabel.LEFT);
// create the corresponding panels
JPanel pingPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
// add the labels onto the panels
pingPanel.add(pingLabel);
v.add(pingPanel);
So the text i want to find is "Hi there"
Then what you need is to check for the elements inside that JPanel. I mean, a panel is a container of UI elements, that said, you need to check for the elements, once you checked for that you need to compare whether it is a label or not, if it is a label then you will be able to get the text of that label.
Can't you show us the code, probably could be easier if you provide the snippet.

Adding text next to a textfield to describe what data the user is expected to enter into it

I am trying to create a simple GUI that simulates a record store. I am still in the beginning stages.
I am running into trouble when I try to add text to describe what the user is expected to enter in the text field.
In addition, I am also having trouble positioning every textfield on its own line. In other words if there is space for two textfields in one line, then it displays in one line, and I am trying to display every text field on its own line.
This is what I tried so far:
item2 = new JTextField("sample text");
However the code above just adds default text within the text field, which is not what I need :/
I appreciate all the help in advance.
public class MyClass extends JFrame{
private JTextField item1;
private JTextField item2;
public MyClass(){
super("Matt's World of Music");
setLayout(new FlowLayout());
item1 = new JTextField();
item2 = new JTextField();
add(item1);
add(item2);
thehandler handler = new thehandler();
item1.addActionListener(handler);
item2.addActionListener(handler);
}
}
For your first problem, you need to use a JLabel to display your text. The constructor is like this:
JLabel label = new JLabel("Your text here");
Works really well in GUI.
As for getting things on their own lines, I recommend a GridLayout. Easy to use.
In your constructor, before adding anything, you do:
setLayout(new GridLayout(rows,columns,x_spacing,y_spacing));
x_spacing and y_spacing are both integers that determine the space between elements horizontally and vertically.
Then add like you have done. Fiddle around with it and you'll get it worked out.
So your final would look like:
setLayout(new GridLayout(2,2,10,10));
add(new JLabel("Text 1"));
add(text1);
add(new JLabel("text 2"));
add(text2);
You could just use a JLabel to label your textfields.
JLabel label1 = new JLabel("Item 1: ");
add(label1);
add(item1);
If you really want text inside the fields, you could set the text in the field with the constructor, and then add a MouseListener to clear the text on click:
item1 = new JTextField("Text");
item1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (item1.getText().equals("Text")) // User has not entered text yet
item1.setText("");
}
});
Or, (probably better) use a FocusListener:
item1 = new JTextField("Text");
item1.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
if (item1.getText().equals("Text")) // User has not entered text yet
item1.setText("");
}
public void focusLost(FocusEvent e) {
if (item1.getText().equals("")) // User did not enter text
item1.setText("Text");
}
});
As for layout, to force a separate line, you use use a Box.
Box itemBox = Box.createVerticalBox();
itemBox.add(item1);
itemBox.add(item2);
add(itemBox);
Make:
item1 = new JTextField(10);
item2 = new JTextField(10);
that should solve problem with width of JTextField.
For beginning use GridLayout to display JTextField in one line. After that I strongly recomend using of MIG Layout http://www.migcalendar.com/miglayout/whitepaper.html.
put JLabel next to JTextField to describe what the user is expected to enter in the text field.
JLabel lbl = new JLabel("Description");
or you could also consider using of toolTipText:
item1.setToolTipText("This is description");
For making a form in Java Swing, I always recommend the FormLayout of JGoodies, which is designed to ... create forms. The links contains an example code snippet, which I just copy-pasted here to illustrate how easy it is:
public JComponent buildContent() {
FormLayout layout = new FormLayout(
"$label, $label-component-gap, [100dlu, pref]",
"p, $lg, p, $lg, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.addLabel("&Title:", CC.xy(1, 1));
builder.add(titleField, CC.xy(3, 1));
builder.addLabel("&Author:", CC.xy(1, 3));
builder.add(auhtorField, CC.xy(3, 3));
builder.addLabel("&Price:", CC.xy(1, 5));
builder.add(priceField, CC.xy(3, 5));
return builder.getPanel();
}
Now for the description:
Use a label in front of the textfield to give a very short description
You can put a longer description in the textfield as suggested by #Alden. However, if the textfield is for short input, nobody will be able to read the description
You can use a tooltip (JComponent#setTooltipText) to put a longer description. Those tooltips also accept basic html which allows some formatting. Drawback of the tooltips is that the user of your application has to 'discover' that feature as there is no clear indication those are available
You can put a "help-icon" (like e.g. a question mark) after each text field (use a JButton with only an icon) where on click you show a dialog with a description (e.g. by using the JOptionPane class)
You can put one "help-icon" on each form which shows a dialog with a description for all fields.
Note for the dialog suggestion: I wouldn't make it a model one, allowing users to open the dialog and leave it open until they are finished filling in the form

Categories

Resources