I need to determine which tabs in a JTabbedPane need updated by determining the contents of each tab's component. From what I can determine, there is no way to iterate through each tab using the default JTabbedPane model.
Does anyone have any ideas as to what I could do in this situation?
if you use something like:
int totalTabs = tabbedPane.getTabCount();
for(int i = 0; i < totalTabs; i++)
{
Component c = tabbedPane.getTabComponentAt(i);
//other stuff
}
Could give you a start point to do what you want.
How about getTabCount() and getTabComponentAt( int index )?
use getComponentAt(int index) from container
Related
Let's suppose I've a list of String like this
List<String> button_names={"Button1","Button2","Button3","Button4"};
I've to insert JButtons with those texts in a JPanel so I do
for (int i=0; i<button_names.length; i++)
myJPanel.add(new JButton(button_name[i]));
My question is... If my model (in this case, my List button_names) changes for any reasons, how can I refresh my JPanel in order to show that change?
Should I do
myJPanel.removeAll()
and insert again my JButtons()? Thank you in adance
Yes removeAll and then reinserting new buttons is the easiest and generally the best way to go. Otherwise, you have to start figuring out which buttons have been removed, which have been added, and where in the list these new buttons are. Also, buttons in the list should change position I guess, so you'd have to cover that case to.
You can write a method like this that you could use in initial creation, and when you want to reload the list
void addButtonsToPanel(JPanel p) {
p.removeAll();
for (int i=0; i<button_names.length; i++)
myJPanel.add(new JButton(button_name[i]));
validate();
repaint();
}
I have a MainJtabbedPane which contains multiple JtabbedPanes each of the JtabbedPanes contain multiple pannels.
I need to be able to access the pannels from the MainJtabbedPane.
JTabbedPane[] components = (JTabbedPane[]) Main_Tabbed_Panel.getComponents();
for(int i=0; i<components.length;i++)
{
for(int j=0;j<components[i].getTabCount();j++)
{
.....
}
}
Giving an error java.awt.component cannot be cast to javax.swing.JtabbedPane
JTabbedPane[] components = (JTabbedPane[]) Main_Tabbed_Panel.getComponents();
The getComponents() method returns an array of Components. You can't just cast them to a JTabbedPane even if you know all the components will be an instance of JTabbedPane. You need to structure your code something like:
for(Component component: main_Tabbed_Panel.getComponents())
{
if (component instanceof JTabbedPane)
{
JTabbedPane tabbePane = (JTabbedPane)component;
// do something with the tabbed pane
}
}
Also, follow Java naming conventions. Variable name should NOT start with an upper case character. (ie. "Main_Tabbed_Pane does not follow conventions).
Switch the (JTabbedPane[]) cast to (Component[]). If you hover over the getComponents() method, you'll see it returns Component[]
If you want to convert that Component[] to JTabbedPane[], you need to do it manually, as well as making sure to check for mistakes along the way (making sure its a JTabbedPane before adding it to a JTabbedPane[])
JTabbedPane[] panes = convertComponents(getComponents());
private JTabbedPane[] convertComponents(Component[] comps) {
JTabbedPane[] panes = comps.length > 0? new JTabbedPane[comps.length] : null;
if(panes != null)
for(int i = 0; i < panes.length; i++) {
if(comps[i] instanceof JTabbedPane)
panes[i] = (JTabbedPane) comps[i];
}
return panes;
}
Although this isn't the most efficient, because for each item that isn't a JTabbedPane in getComponents(), there will be an empty spot in your JTabbedPane array, which you then have to clean up.
JTabbedPane[] panes = comps.length > 0? new JTabbedPane[comps.length] : null;
This first checks if the Component[] passed through the parameters has 1 or more spaces. If not, dont bother initializing with an instance.
if(panes != null)
Since theres a chance panes could initialize as null, we much check before trying to use it
for(int i = 0; i < panes.length-1; i++) {
Since Component[] comps and JTabbedPane[] panes have the same size, it doesn't matter which length you use, as long as we know how many times to loop.
if(comps[i] instanceof JTabbedPane)
This is what I meant where I said "if the component isn't a JTabbedPane, you will have a null space in your array". This will check if it's a JTabbedPane before putting it in our panes array. If not, it's ignored completely, and that space in panes is left as null
After the loop is complete, it will return the array we just made.
I'm trying to create a home replacement application and I want to know my options, I could use a TableLayout or nested LinearLayouts but the icon size and number of rows and columns of icons can change so I'm looking for something easier to manage, maybe just one layout and have items accomodate automatically somehow.
In HTML div you can use float:left and if you append items on a container they accomodate like this:
Is there a way to do something similar in Java? If not what is the recommended way to create a grid layout?
I ended up using a set of <LinearViews> and appending buttons directly on them, I think it's the easiest method if the number of rowsXcols can vary.
for(int c = 0; c < appCols; c++) { // Go through cols
LinearLayout col = new LinearLayout(context);
col.setOrientation(LinearLayout.VERTICAL);
for(int r = 0; r < appRows; r++) { // Go through rows
Button button = new Button(context);button.setText(allApps.get(n).activityInfo.loadLabel(pm).toString());
button.setWidth(iconWidth);
button.setHeight(iconHeight);
// add app icon
col.addView(button);
n++;
}
// Add column
layout.addView(col);
}
I have a problem regarding loops. I need to access 10 labels which have names like label1, label2, label3 .... etc. I need to know whether I can access those labels by going through a loop in java?
How about using List or an array
List<JLabel> labels = new ArrayList<JLabel>();
labels.get(index);
Change those labels to be an array, and access it using an index.
For example:
JLabel[] labels = new JLabel[10];
for (int i = 0; i < labels.length; ++i) {
labels[i] = new JLabel("Label " + i);
}
for (int i = 0; i < labels.length; ++i) {
// access each label.
}
Put your labels in to LinkList or array
Then you can access those array or linkList on a loop
If you cannot change the labels names / put them into an array you can make an array of references to the labels and fill it at the beginning of your program with the list of your labels.
'Access to labels' is kinda vague. Are you referring to different instances of java.awt.label? If so you can simply loop over them when they're in a list with a for-each statement.
If you are talking about Java labels, you can use a switch statement instead. If you are talking about objects such as a JLabel, use an array or ArrayList.
I am currently writing a sudoku solver in Java. What I need now is some kind of Swing GUI to input the known numbers. I created a JFrame, but manually adding 81 text fields from the toolbox seems like a bad solution. I am also able to add with code like this:
this.setLayout(new GridLayout(9, 9));
for (int i = 0; i < 81; i++)
{
this.add(new JTextField("Field"));
}
However, I do not know how to address these text fields afterwards to collect the user input into a two-dimensional array. How can I do that?
A different solution would be to use a JTable. You could allow for the TableModel to maintain the full data solution, as well as a copy of the user's attempts. The CellRenderers and CellEditors could handle the user experience. See this tutorial.
Struggled a bit with this for my own sudoku solver, but ended up going for painting on a JPanel, and adding a mouse listener to that.. Than determine the current field using mouse position with his function:
addMouseListener(new MouseAdapter() {
private int t(int z) {
return Math.min(z / factor, 8);
};
#Override
public void mouseMoved(MouseEvent e) {
setToolTipPossibilities(t(e.getX()), t(e.getY()));
}
#Override
public void mousePressed(MouseEvent e) {
clickColumn = t(e.getX());
clickRow = t(e.getY());
}
});
First you need to declare array of JTextFields.
So just like your array to store user input you do:
private JTextField[] textFields;
After that you can use some math to map your one-dimensional array to your two dimensions.
something like this should work:
floor(index / 9), index % 9
for x,y
Yes that will work to display the array. To read from the array you just need to call the getText method for each element.
JTable is your friend. Use a DefaultTableModel with editable String values.
String[] columnNames = new String[9];
for(int i=0; i<9; i++){columnNames[i]="";}
String[][] data = new String[9][9];
JTable tab = new JTable(columnNames,data);
When they fill it in, check that each string is an appropriate number and prompt for error.
1st way:
You could put the text fields into an array that mirrors the array that your cell values are in.
The problem with this method tho is that when you need to bind a mouseListener or ActionListener to the TextField you will have a hard time figuring out which cell number it corrisponds to.
2nd way:
You could extend the JTextField into a custom class with new instance variables that store cell number in it.
Using this method you can also implement MouseListener or ActionListener on the extended class too and get whatever information about the field you need, without searching through your array. And combining with the first to put them into an array organizes them for quick access.
Just want to post a little update.
I added an array of textfields as a field on my form:
private JTextField[] fields;
Initialized it:
fields = new JTextField[81];
And finally I am adding the fields to my form like this:
private void addComponents()
{
this.setLayout(new GridLayout(9, 9));
for (int i = 0; i < fields.length; i++)
{
fields[i] = new JTextField("" + i);
this.add(fields[i]);
}
}
The result as of now can be seen here:
Image of my textfields