JTabbedPane created dynamically - java

I have a problem when I try to crete dynamically Tabs on a JTabbePane by a for. The problem is that I don't know how to access the contents when an event happens.
I will try to show you part of the code to be easy to understand.
conteudoT = new JTabbedPane(JTabbedPane.TOP);
conteudoT.setBounds(5, 19, 477, 232);
for (int i = 0; i < players; i++) {
conteudo = new JPanel();
conteudo.setLayout(null);
Details = new JPanel();
Details.setBounds(15, 11, 307, 183);
Details.setVisible(false);
Details.setName("Details" + i);
conteudo.add(Details);
btnR = new JButton("r");
btnR.addActionListener(this);
conteudoT.addTab("Jogador " + (i + 1), conteudo);
Details.setLayout(new GridLayout(2, 1, 0, 0));
...
contentPane.add(conteudoT);
}
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < players; i++) {
if (e.getSource()==btnR) {
Details.setVisible(true);
}
}
}
What happens here is that the painel Details is added on the last Tab to be constructed and I would like to add it on the Tab that the event happend.

use :
conteudoT.indexOfTab(string)
to get the index. Then use :
conteudoT.getTabComponentAt(int index)
to get the component

Related

Java - Adding Arrays of JTextField and JLabel to a JPanel

I'm hoping this is an easy question. I have a JComboBox with the choices of 0, 1, 2, 3,...10. Depending on what number is selected in the JComboBox, I want my GUI to add a JLabel and a JTextField. So if the number 3 is chosen, the GUI should add 3 JLabels and 3 JTextFields. and so forth.
I'm using an array of JLabels and JTextFields to accomplish this, but I am getting a null pointer exception at runtime, and no labels or fields are being added.
Code:
private void createComponents()
{
//Create Action Listeners
ActionListener comboListener = new ComboListener();
//Create Components of the GUI
parseButton = new JButton("Parse Files");
parseButton.addActionListener(comboListener);
numberLabel = new JLabel("Number of Files to Parse: ");
String[] comboStrings = { "","1", "2","3","4","5","6","7","8","9","10" };
inputBox = new JComboBox(comboStrings);
inputBox.setSelectedIndex(0);
fieldPanel = new JPanel();
fieldPanel.setLayout(new GridLayout(2,10));
centerPanel = new JPanel();
centerPanel.add(numberLabel);
centerPanel.add(inputBox);
totalGUI = new JPanel();
totalGUI.setLayout(new BorderLayout());
totalGUI.add(parseButton, BorderLayout.SOUTH);
totalGUI.add(centerPanel, BorderLayout.CENTER);
add(totalGUI);
}
ActionListener Code:
public void actionPerformed(ActionEvent e)
{
JTextField[] fileField = new JTextField[inputBox.getSelectedIndex()];
JLabel[] fieldLabel = new JLabel[inputBox.getSelectedIndex()];
for(int i = 0; i < fileField.length; i++)
{
fieldLabel[i].setText("File "+i+":"); //NULL POINTER EXCEPTION HERE
fieldPanel.add(fieldLabel[i]); //NULL POINTER EXCEPTION HERE
fieldPanel.add(fileField[i]);
}
centerPanel.add(fieldPanel);
repaint();
revalidate();
}
Thanks to MadProgrammer's comment, this question has been answered.
Editing the loop to:
for(int i = 0; i < fileField.length; i++)
{
fieldLabel[i] = new JLabel();
fileField[i] = new JTextField();
fieldLabel[i].setText("File "+i+":");
fieldPanel.add(fieldLabel[i]);
fieldPanel.add(fileField[i]);
}
resolved the issue.

ScrollPane adding to grid layout

in my code I am calling a few items(my buttons with their names leading to different project. The names and everything are taken from a database)
I want a J ScrollPane to surround my buttons, what can I do? I just want the buttons to be called inside the scroll pane. Here is my code
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AdminClass implements ActionListener {
ProjectButton[] buttons = new ProjectButton[35];
//Creating data field for unique Ids in the form of array list
ArrayList<Integer> uniqueIDList = new ArrayList<Integer>();
String[] projectNames;
int[] uniqueIds;
Connection conn1 = null;
Statement stmt1 = null;
JFrame frame = new JFrame("Admin Panel");
private JPanel panel = new JPanel();
JButton btnNewButton = new JButton("Add New Project");
public AdminClass() {
panel.setLayout(new GridLayout(10, 1));
panel.add(new JLabel("Welcome to Admin Panel"));
btnNewButton.addActionListener(this);
panel.add(btnNewButton);
panel.add(new JLabel("Existing Projects"));
conn1 = sqliteConnection.dbConnector();
try{
Class.forName("org.sqlite.JDBC");
conn1.setAutoCommit(false);
stmt1 = conn1.createStatement();
ResultSet rs1 = stmt1.executeQuery( "SELECT * FROM Project;" );
List<String> projectNameList = new ArrayList<String>();
while ( rs1.next() ){
int id = rs1.getInt("uniqueid");
String projectName = rs1.getString("name");
projectNameList.add(projectName);
uniqueIDList.add(id);
}
// Converting array list to array
projectNames = new String[projectNameList.size()];
projectNameList.toArray(projectNames);
uniqueIds = convertIntegers(uniqueIDList);
rs1.close();
stmt1.close();
conn1.close();
}
catch ( Exception e1 ) {
JOptionPane.showMessageDialog(null, e1);
}
// Adding buttons to the project
try{
for (int i = 0; i < projectNames.length; i++){
buttons[i] = new ProjectButton(projectNames[i]);
buttons[i].setId(uniqueIds[i]);
panel.add(buttons[i]);
buttons[i].addActionListener(this);
}
}
catch (Exception e2){
JOptionPane.showMessageDialog(null, e2);
}
frame.add(panel);
frame.setVisible(true);
frame.setSize(500, 500);
}
public void actionPerformed(ActionEvent e) {
for (int j = 0; j < buttons.length; j ++){
if (e.getSource() == buttons[j]){
AdminStatus sc = new AdminStatus(buttons[j].getId());
frame.dispose();
}
}
if (e.getSource() == btnNewButton){
frame.dispose();
WindowProjectAdmin wpa = new WindowProjectAdmin();
}
}
//Method to convert integar array list to integar array
public int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
}
This may seem very normal but it's really not, for some reason they are not visible or are not called inside a scroller. Please edit my code maybe?
Start by adding the buttons to their own container, this way you can control the layout of the buttons separately from the rest of the UI
JPanel panelFullOfButtons = new JPanel();
try {
for (int i = 0; i < projectNames.length; i++) {
buttons[i] = new ProjectButton(projectNames[i]);
buttons[i].setId(uniqueIds[i]);
panelFullOfButtons.add(buttons[i]);
buttons[i].addActionListener(this);
}
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, e2);
}
Then add the "main" panel to the NORTH position of the frame and the "buttons" panel to the CENTER
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(panelFullOfButtons), BorderLayout.CENTER);
Mind you, in this case, I'd be very tempted to use something like a JList instead. See How to Use Lists for more details
I have done the same, can you tell me what's wrong?
// Problem #1...
JScrollPane pane = new JScrollPane();
pane.add(buttonPanel);
//...
// Problem #2...
panel.add(pane);
frame.add(panel);
These are competing with each other, moving the content around and overlapping with existing content...
public AdminClass() {
panel.setLayout(new GridLayout(3, 1));
panel.add(new JLabel("Welcome to Admin Panel"));
btnNewButton.addActionListener(this);
panel.add(btnNewButton);
panel.add(new JLabel("Existing Projects"));
List<String> projectNameList = new ArrayList<String>();
for (int index = 0; index < 1000; index++) {
projectNameList.add("Project " + index);
}
projectNames = projectNameList.toArray(new String[0]);
// Adding buttons to the project
buttons = new JButton[projectNameList.size()];
try {
for (int i = 0; i < projectNames.length; i++) {
buttons[i] = new JButton(projectNames[i]);
btnPnl1.add(buttons[i]);
buttons[i].addActionListener(this);
}
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, e2);
}
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(btnPnl1), BorderLayout.CENTER);
frame.setVisible(true);
frame.setSize(500, 500);
}
In this case I'd prefer to use either a JList to show the projects or a WrapLayout for laying out the buttons
Its useless to create a GridLayout like this: panel.setLayout(new GridLayout(10, 1));. If you declare the rows as a non zero value, the column count will be ignored. When you declare the maximum number of rows as ten, you force the eleventh component to be added in a second column (then a third, a forth and so on). Use panel.setLayout(new GridLayout(0, 1)); instead to force the only one column and frame.add(new JScrollPane(panel)); to create the ScrollPane.
But note that GridLayout will try to shrink your components the maximum as possible to fit the container size before scrolling is enabled.
I just want the button part to be inside J Scroll Pane
If you just want the JButton's (those added within the loop):
Create a new JPanel that you add the buttons to
Add (1) to a JScrollPane
Add (2) to panel
For example:
JPanel buttonPanel = new JPanel(new FlowLayout());
for (int i = 0; i < projectNames.length; i++){
buttons[i] = new ProjectButton(projectNames[i]);
buttons[i].setId(uniqueIds[i]);
panel.add(buttons[i]);
buttonPanel[i].addActionListener(this);
}
JScrollPane scroller = new JScrollPane(buttonPanel);
panel.add(scroller);
You might also consider using a different Component that doesn't require a JScrollPane, of course depending upon your needs - for instance a JComboBox.

Refresh JPanel with another values

Today I started to learn Java and I'm stuck here, I don't know how to refresh the panel using a button. Here is my code:
import java.awt.GridLayout;
import java.util.Random;
import javax.swing.*;
public class App {
public static int STR = 0, aPower = 0, sPower = 0, INT = 0, STA = 0, DEF = 0;
private static void GenerateStatus(){
Random randomGenerator = new Random();
STR = randomGenerator.nextInt(50);
aPower = randomGenerator.nextInt(50);
sPower = randomGenerator.nextInt(50);
INT = randomGenerator.nextInt(50);
STA = randomGenerator.nextInt(50);
DEF = randomGenerator.nextInt(50);
}
private static void FirstTimeInGame() {
String[] items = {"Warrior", "Mage", "Druid", "Scout"};
JComboBox combo = new JComboBox(items);
JTextField Name = new JTextField();
JPanel panel = new JPanel(new GridLayout(0, 1));
GenerateStatus();
panel.add(new JLabel("Name", SwingConstants.CENTER));
panel.add(Name);
panel.add(new JLabel("Class", SwingConstants.CENTER));
panel.add(combo);
panel.add(new JLabel("Stats", SwingConstants.CENTER));
panel.add(new JLabel("Strength " + STR));
panel.add(new JLabel("Attack Power " + aPower));
panel.add(new JLabel("Spell Power " + sPower));
panel.add(new JLabel("Intellect " + INT));
panel.add(new JLabel("Stamina " + STA));
panel.add(new JLabel("Armor " + DEF));
String[] buttons = {"Create!", "Randomize!", "Cancel"};
int result = JOptionPane.showOptionDialog(null,
panel,
"Welcome",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
buttons,
buttons[2]
);
if (result == JOptionPane.OK_OPTION) {
System.out.println(combo.getSelectedItem()
+ " " + Name.getText());
}
else if (result == JOptionPane.NO_OPTION){
GenerateStatus();
panel.validate();
panel.repaint();
}
else{
System.out.println("CANCEL");
}
}
public static void main(String[] args) {
FirstTimeInGame();
}
}
Function GenerateStatus() generate random numbers. When I press the button 'Randomize!' the window is closing.
Anyone can help me? Please?
Instead of just adding the JLabels to a panel, you need to store them in class level members.
When you click a button, you need to change the text in the existing labels.
Near this:
public static int STR = 0, aPower = 0, sPower = 0, INT = 0, STA = 0, DEF = 0;
Add
private JLabel strLabel;
Then panel.add(new JLabel("Strength " + STR)); becomes
strLabel = new JLabel("Strength " + STR);
panel.add(strLabel);
Now you can change the text of strLabel from somewhere else.

Listbox in Java

I was trying to build the Font window of Notepad using Java using the code shown below. But, I'm facing a problem in setting the size of the text as specified inside listbox.
I'm trying to get the respective size corresponding to the index of the selected item but couldn't find any such method.
f = new Frame("Font");
f.setLayout(new GridLayout(3, 3));
b1 = new Button("OK");
l1 = new Label("Font :");
l2 = new Label("Size :");
l3 = new Label("Font Style :");
lb1 = new List(10, false);
lb2 = new List(10, false);
lb3 = new List(5, false);
String [] s = {"Times New Roman", "Arial", "Verdana", "Trebuchet MS", "Papyrus","Monotype Corsiva","Microsoft Sans Serif", "Courier", "Courier New"};
for(int i = 0; i < s.length; i++)
{
lb1.add(s[i]);
}
for(int i = 8; i <=72; i += 2)
{
lb2.add(i + "");
}
String [] s1 = {"BOLD", "ITALIC", "PLAIN"};
for(int i = 0; i < s1.length; i++)
{
lb3.add(s1[i]);
}
f.add(l1);
f.add(l2);
f.add(l3);
f.add(lb1);
f.add(lb2);
f.add(lb3);
f.add(b1);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
if(lb3.isIndexSelected(0))
fo = new Font(lb1.getSelectedItem(), Font.BOLD, **lb2.getSelectedIndex**());
else if(lb3.isIndexSelected(1))
fo = new Font(lb1.getSelectedItem(), Font.ITALIC, lb2.getSelectedIndex());
else
fo = new Font(lb1.getSelectedItem(), Font.PLAIN, lb2.getSelectedIndex());
ta1.setFont(fo);
MyFrame15.f.dispose();
}
});
f.setSize(300, 300);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int)((d.getWidth() / 2) - 200);
int y = (int)((d.getHeight() / 2) - 200);
f.setLocation(x, y);
f.setVisible(true);
}
To get the size as required by user we can use:
lb2.getSelectedItem();
which returns a String but the third argument of Font constructor requires an integer.Therefore, we use parseInt() method of Integer class to convert the string received to integer.The code is as follows:
Font(lb1.getSelectedItem(), Font.BOLD, Integer.parseInt(lb2.getSelectedItem()));
I would suggest you use Swing for this. You can start with the Swing tutorial on Text Component Features which already contains a working example that does what you want.

java.lang.IndexOutOfBoundsException: Index: 6, Size: 6 JAVA, ARRAY

I realize this is an unbelievably common issue and have looked very very thoroughly but have had no luck! It seems I am having an outOfBounds Exception issue. My code is as follows wuth errors just after! Thanks again :)
UPDATE:
Thanks for all of your many fast responses. Although it says there's an issue with Analysis Panel, I didn't know exactly if this was the cause as I have other classes which use it with no issues! But below is the other code. Thanks again!
public class AnalysisPanel extends JPanel {
private JTextArea overview_text = GuiComponentGenerator.getJTextArea("");
private JTextArea csv_text = GuiComponentGenerator.getJTextArea("");
private JComboBox analyser_choices;
private String[] analyser_class_names;
private LinkedHashMap<String, ImageAnalysis> analyser_outputs = new LinkedHashMap();
private JTextField[] weka_directory_texts;
private JTextField[] weka_tag_texts;
private JTextField weka_output_file_path_text = GuiComponentGenerator
.getJTextField("");
private JTextField weka_relation_text = GuiComponentGenerator
.getJTextField("");
public AnalysisPanel() {
GuiComponentGenerator.setLook(this);
analyser_class_names = ResourceAndClassDirectories
.getClassNamesInDirectory(ResourceAndClassDirectories.IMAGE_ANALYSERS_CLASS_STEM);
ArrayList<String> choices = new ArrayList(
Arrays.asList(analyser_class_names));
choices.add(0, "All");
analyser_choices = GuiComponentGenerator.getJComboBox(choices);
analyser_choices.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateTextBoxes();
}
});
setLayout(new BorderLayout());
add(BorderLayout.NORTH,
GuiComponentGenerator.getJPanel(analyser_choices));
add(BorderLayout.CENTER, getTextsPanel());
add(BorderLayout.SOUTH, getWekaPanel());
}
private JPanel getWekaPanel() {
JPanel weka_panel = GuiComponentGenerator.getJPanel(new BorderLayout());
JPanel details_panel = GuiComponentGenerator.getJPanel(new GridLayout(
6, 1));
JPanel top_panel = GuiComponentGenerator
.getJPanel(new GridLayout(1, 2));
JPanel left_top_panel = GuiComponentGenerator.getJPanel(new BorderLayout());
JPanel right_top_panel = GuiComponentGenerator.getJPanel(new BorderLayout());
left_top_panel.add(BorderLayout.WEST, GuiComponentGenerator.getJLabel("Relation:"));
left_top_panel.add(BorderLayout.CENTER, weka_relation_text);
right_top_panel.add(BorderLayout.WEST, GuiComponentGenerator.getJLabel("Output to:"));
right_top_panel.add(BorderLayout.CENTER, weka_output_file_path_text);
top_panel.add(left_top_panel);
top_panel.add(right_top_panel);
weka_panel.add(BorderLayout.NORTH, top_panel);
weka_directory_texts = new JTextField[5];
weka_tag_texts = new JTextField[5];
JPanel labels_panel = GuiComponentGenerator.getJPanel(new GridLayout(1,
2));
labels_panel.add(GuiComponentGenerator.getCentreAlignedJLabel("Tag"));
labels_panel.add(GuiComponentGenerator
.getCentreAlignedJLabel("Image directory"));
details_panel.add(labels_panel);
for (int pos = 0; pos < 5; pos++)
details_panel.add(getDetailsPanel(pos));
weka_panel.add(BorderLayout.NORTH, top_panel);
weka_panel.add(BorderLayout.CENTER, details_panel);
JPanel weka_bordered_panel = GuiComponentGenerator
.getLeftBorderedJPanel(weka_panel, "Weka");
return weka_bordered_panel;
}
private JPanel getDetailsPanel(int pos) {
JPanel details_panel = GuiComponentGenerator.getJPanel(new GridLayout(
1, 2));
final JTextField weka_directory_text = GuiComponentGenerator
.getJTextField("");
JTextField weka_tag_text = GuiComponentGenerator.getJTextField("");
weka_directory_texts[pos] = weka_directory_text;
weka_tag_texts[pos] = weka_tag_text;
JPanel right_panel = GuiComponentGenerator
.getJPanel(new BorderLayout());
right_panel.add(BorderLayout.CENTER, weka_directory_text);
JButton choose_directory_button = GuiComponentGenerator
.getJButton(GuiComponentGenerator.FILE_DIALOG_ICON);
right_panel.add(BorderLayout.EAST, choose_directory_button);
choose_directory_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
File directory = FileChooserDialog.getFile(
ResourceAndClassDirectories.SOURCE_DIRECTORY, "", true);
if (directory != null)
weka_directory_text.setText(directory.getPath());
}
});
details_panel.add(weka_tag_text);
details_panel.add(right_panel);
return details_panel;
}
public String[] getWekaRunDetails() {
String[] wrd = { weka_relation_text.getText(),
weka_output_file_path_text.getText() };
return wrd;
}
public ArrayList<String[]> getWekaImageDetails() {
ArrayList<String[]> image_details = new ArrayList();
for (int pos = 0; pos < 5; pos++) {
String[] details = { weka_directory_texts[pos].getText(),
weka_tag_texts[pos].getText() };
image_details.add(details);
}
return image_details;
}
private JPanel getTextsPanel() {
JPanel texts_panel = GuiComponentGenerator
.getJPanel(new BorderLayout());
csv_text.setRows(3);
csv_text.setFont(new Font("Courier", Font.PLAIN, 14));
texts_panel.add(BorderLayout.NORTH, GuiComponentGenerator
.getLeftBorderedJPanel(
GuiComponentGenerator.getJScrollPane(csv_text), "CSV"));
texts_panel.add(BorderLayout.CENTER, GuiComponentGenerator
.getLeftBorderedJPanel(
GuiComponentGenerator.getJScrollPane(overview_text),
"Overview"));
return texts_panel;
}
public String getChosenImageAnalyser() {
return (String) analyser_choices.getSelectedItem();
}
public void performAnalyses(final TaggedBufferedImage tbi) {
Thread thread = new Thread() {
public void run() {
analyser_outputs.clear();
String choice = (String) analyser_choices.getSelectedItem();
csv_text.setText("");
if (choice.equals("All")) {
for (String analyser_class_name : analyser_class_names)
performAnalysis(analyser_class_name, tbi);
} else
performAnalysis(choice, tbi);
updateTextBoxes();
}
};
thread.start();
}
private void updateTextBoxes() {
String overview = "";
String csv_headings = "|";
String csv_values = "|";
String choice = (String) analyser_choices.getSelectedItem();
for (String analyser_class_name : analyser_class_names) {
if (choice.equals("All") || choice.equals(analyser_class_name)) {
ImageAnalysis image_analysis = analyser_outputs
.get(analyser_class_name);
if (image_analysis != null) {
overview += analyser_class_name + "\n\n"
+ image_analysis.overview + "\n-----------------\n";
System.out.println("In Analysis Panel: image analsis csv headings " + image_analysis.csv_headings.size());
for (int pos = 0; pos < image_analysis.csv_headings.size(); pos++) {
String heading = image_analysis.csv_headings.get(pos);
String value = image_analysis.csv_values.get(pos);
while (heading.length() < value.length())
heading += " ";
while (value.length() < heading.length())
value += " ";
csv_values += value + "|";
csv_headings += heading + "|";
}
}
}
}
overview_text.setText(overview);
csv_text.setText(csv_headings + "\n" + csv_values);
}
private void performAnalysis(String analyser_class_name,
TaggedBufferedImage tbi) {
try {
overview_text.setText("Analysing " + analyser_class_name);
Class c = Class
.forName(ResourceAndClassDirectories.IMAGE_ANALYSERS_CLASS_STEM
+ "." + analyser_class_name);
ImageAnalyserInterface analyser = (ImageAnalyserInterface) c
.newInstance();
ImageAnalysis image_analysis = analyser.analyseImage(tbi);
analyser_outputs.put(analyser_class_name, image_analysis);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Update: Now working, although the issue was in the below, it needed to be changed in the Colour file itself!
Thanks all :)
If there are 6 elements in the array, then index 5 will be the final index, as it is zero indexed - that is, 0,1,2,3,4,5 is 6 elements
Well based on the title you are trying to access index 6 in an array of size 6. This is not possible since arrays in Java run from index 0 to size-1.
Your max possible index is therefore 5 in an array of size 6.

Categories