Java Swing addTab with count - java

Some swing components i have:
//JList
DefaultListModel listModel = new DefaultListModel();
JList list = new JList(listModel);
//JTabbedPane
JTabbedPane tabbedPane = new JTabbedPane();
frame.add(tabbedPane);
//JSplitPane split
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,list , tabbedPane);
splitPane.setDividerLocation(200);
frame.add(splitPane);
//JScrollPane & JTextPane to go inside the tabbed panes
JTextPane textPane = new JTextPane();
textPane.setFont(new Font("Calibri",Font.PLAIN,14));
JScrollPane scrollPane = new JScrollPane(textPane);
When a user "Opens" a text file, it should display it on a JList and on the JTextPane inside of the JTabbedPane. This is what I've tried:
int count = tabbedPane.getTabCount();
//Add the selected file's name as a string to tabbedPane & listModel.
tabbedPane.addTab(file, scrollPane);
tabbedPane.setSelectedIndex(count);
listModel.addElement(file);
list.setSelectedIndex(count);
The error I get:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Tab count: 1
I've been told to keep a reference to the original tabbed pane so that the code in an ActionListener can reference this variable and add more - but I didn't understand this (I'm new). Any help would be highly appreciated.

list.setSelectedIndex(count);
Java indexes are zero based. The code should be:
list.setSelectedIndex(count - 1);
I've been told to keep a reference to the original tabbed pane
and you are still not doing that.
JTabbedPane tabbedPane = new JTabbedPane();
That is a local variable, not an instance variable. How does that code look like the code from the link I provided you with in your last question???
Local variables and instance variable are basic Java. If you don't understand these you should not be working with a GUI. Read your text book first for Java basics. Read the tutorial link I gave you. Download the working code and take the time to understand it!!!

Related

how can I place an element of a jPanel over another in Java?

I'm using the graphic tool of netbeans and I have a JPanel on which I put a JTextArea.
Then, I need to create a JList on the JTextArea, but it is created below.
https://gyazo.com/7f8c3613317b49e72edea34c040115c1
Is there any way to sort the elements of a JPanel or how can I do it?
Thank you
The basic code would be something like:
int offset = textArea.getCaretPosition();
Rectangle location = textArea.modelToView(offset);
JList list = new JList(...);
list.setVisibleRowCount(...);
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setSize(scrollPane.getPreferredSize();
scrollPane.setLocation(location.x, location.y);
textArea.add(scrollPane);
Once you select an item from the list you would then need to remove the scrollpane from the text area.

Using a function to create multiple components and change line automatically [Java]

So i lost some hours already with this and i can't seem to find a solution.
Basically i have a Jframe and inside, i have a Scrollpane and a panel
I have 1 Jlabel, 1 JTextField and 1 JButton inside that panel in a single line.
The JButton can add a new JLabel, a new JTextField and a new JButton, but i can't get them to be positioned in the next line.
I have been messing around with the layouts, but none of them fits my needs, and unfortunaly i never understand or learned how the GUI of java Works.
How's the best way to just keep adding those componentes (Jlabel, Jtextfields and Jbuttons) on a next line for every click i made?
This is my code:
private void BtnaddvariableActionPerformed(java.awt.event.ActionEvent evt) {
JLabel Lblvariablextra = new JLabel("Testing");
PanelVariable.add(Lblvariablextra);
ScrollPaneVariable.setViewportView(PanelVariable);
}
The code only contains an exemple of the label tough.
Create a main panel that is added to the scroll pane when the GUI is created:
Box main = Box.createVerticalBox();
scrollPane.setViewportView( main );
Then in the ActionListener you create a child panel contain the 3 components every time the button is pressed:
JPanel child = new JPanel();
child.add( new JLabel("I'm a label") );
child.add( new JTextField(10) );
child.add( new JButton("Click Me") );
main.add(child);
Read the section from the Swing tutorial on Layout Manager to understand how layout management works.

Adding every element in a ArrayList to a JFrame

So I want to add some text to a window.
I added the text in a ArraList like this:
ArrayList<String> Text = new ArrayList<String>();
Text.add("text1");
Text.add("text2");
...
Text.add("text*n*");
I now want to add these items into a JFrame. Now, I am pretty new to programming, so there is probably a better solution than this. But here is what I tried (I am using a for loop, because I think this is also the easiest way for me to manage the bounds of the labels:
for(int i = 0; i<Text.size();i++){
JLabel jl = new JLabel(names.get(i));
jl.setBounds(50,100+20*i,200,50);
this.add(jl);
}
But only the last element in the ArrayList is added to the JFrame (text*n*). Not all of them.
How can I get every element in the arraylist to show in the jframe? Maybe I shouldn't use JFrame?
It sounds like you want to use a JList, not a grid of JLabel.
i.e.,
DefaultListModel<String> listModel = new DefaultListModel<String>();
JList<String> myJList = new JList<String>(listModel);
// assuming you have an array of String or ArrayList<String> called texts
for (String text : texts) {
listModel.addElement(text);
}
JScrollPane listScrollPane = new JScrollPane(myJList);
// then add the listScrollPane to your GUI
Also:
Please learn and follow Java naming rules. Variable names should begin with a lower case letter, so "text" not Text.
And you should know that every time someone uses a null layout and setBounds(...) a puppy dies. Please don't be cruel to puppies, and don't create rigid hard to maintain and upgrade GUI's. Learn and use the Swing layout managers. You won't regret this, and neither will the puppies.
You need a layout, otherwise they are added on top of each other. Try adding everything to a JPanel and only add the panel to the frame at the end.
JFrame frame = new JFrame("title");
JPanel panel = new JPanel();
// Y_AXIS means each component added will be added vertically
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (String str : Text) {
JLabel j1 = new JLabel(str);
panel.add(j1);
}
frame.add(panel);
frame.pack();
frame.setVisible(true);
Try with Replace names.get(i) as Text.get(i)
OR Try,
for(String str : Text){
JLabel jl = new JLabel(str);
}
Try this:
String output = "";
for(int i = 0; i<Text.size();i++)
{
output += Text.get[i] + "\n";
}
JLabel jl = new JLabel(output);
This will create a string named output that will add the text from each index, followed by creating a new line. Then at the end, the full string will be added to the JLabel. The only downside to this method is that one label will contain ALL of the text.
JLabel jl = new JLabel(names.get(i));
Here you always construct a new object for j1, and after the loop you just have the latest object.

Java Styling - Spacing

So I've been learning Java for the very first time and it's time for me to attempt my first project. And I'm stuck at the "first hurdle" haha.
The issue I have is the fact that I don't actually know how to space J Items apart.
I have a 250,350 window for a Log In form with a JLabel, a JTextField for username and JLabel JPassword for Password with a JButton at the bottom.
What I want to do now is style it so that the spacing between the top and the bottom of the form makes it so that the form is centered as well as adding a line's height space between the JLabel and the JTextField. (Basically a \n type deal but that isn't working.)
Hopefully this makes sense, if not, I apologise and I'll try to rephrase/add code!
public Game() {
this.setSize(250,350);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Sticket Cricket - Login");
JPanel loginMenuPanel = new JPanel();
loginButton = new JButton("Login");
usernameField = new JTextField();
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setColumns(10);
passwordField.requestFocus();
usernameLabel = new JLabel("Username: ");
passwordLabel = new JLabel("Password: ");
this.add(loginMenuPanel);
loginMenuPanel.add(usernameLabel);
loginMenuPanel.add(usernameField);
loginMenuPanel.add(passwordLabel);
loginMenuPanel.add(passwordField);
loginMenuPanel.add(loginButton);
this.setVisible(true);
}
Short Answer:
Create a JPanel, set the layoutmanger of the panel (some examples, GridLayout, BorderLayout, Check out the tutorial here where more of these are explained)
Then add your components to this panel accordingly
For the layout you are looking for it would possibly be easier to use an IDE to create this, I find Net Beans to be the easiest for doing this.
My recommendation would be for you to create a JPanel with a grid layout of 2 columns and 2 rows, to this add you JLabels and Text fields for the logon name and password.
Then create another JPanel possibly BorderLayout or Flow Layout and add the above panel to this then add this parent panel to the frame.

scrollpane blocks buttons in BorderLayout?

I have a really weird problem with a JScrollPane and a BorderLayout. For short explaination: i have a JTable which is inside the JScrollPane and this is with a JPanel and the JTableHeader on a JTabbedPane. Very Simple Layout. If i add just the JTable to my JPanel, the buttons are working. If i add the JScrollPane, the Buttons are not working anymore, so i cant click them! The ActionLister is never reached and i cant see the click-animation.
Some Sample code to explain:
d_pane = new JPanel();
d_button = new JPanel();
d_pane.add(table.getTableHeader(), BorderLayout.PAGE_START);
dl_scroll = new JScrollPane(table);
d_pane.add(dl_scroll, BorderLayout.CENTER);
// d_button is ridLayouted with 3 Buttons in there
d_pane.add(d_button, BorderLayout.PAGE_END);
1) The JScrollPane takes care of the table header itself. Don't add it to the pane.
2) the button does not seem to get the mouse events, probably because another component is above it - do you have other components/code in the setup?

Categories