Я думаю, что вы пытаетесь использовать вложенный JPanels
. Это, безусловно, способ организации ваших компонентов, но недостатком является то, что в некоторых случаях им трудно управлять. Вы можете попробовать этот фрагмент кода ниже. В программе вы найдете:
1) Массив JLabel
2) Массив JTextField
3) Вложенный JPanels
В конце программы я использую Container
, чтобы добавить конечный продукт этих объектов в мое графическое окно.
Самый эффективный способ, который я могу придумать, - это определить эти компоненты в верхней части моей программы, чтобы я мог использовать их позже, когда мне нужно.
Для этого вы можете попробовать этот фрагмент кода:
import javax.swing.*; //Required to use Swing Components
public class TestGUI extends JFrame
{
JLabel[] label; //Define this with an array
JTextField[] textField; //Define this with an array as well
private int nLabels; //Number of labels preferred
private int nTextFields; //Number of text fields preferred
public testGUI(int amt)
{
//Assuming that you want equal amounts of each,
//set these two variables to the "ant" input parameter
nLabels = amt;
nTextFields = amt;
//Set component attributes
label = new JLabel[2]; //Label compared text fields
textField = new JTextField[2]; //Use two of these for comparison
textField[0].setEnabled(false); //Disabled editing
//Do nothing with the second text field
JPanel labels = new JPanel(); //Place JLabels here
//Use this to align the labels vertically
labels.setLayout(new GridLayout(2, 1));
//Use this for loop to add the labels to this JPanel
for(int i = 0; i < nLabels; i++)
{
labels.add(label[i]);
//You can also define and apply additional properties
//to labels inside this loop. TIP: You can do this in
//any loop
}
JPanel txtFields = new JPanel(); //Place JTextFields here
//Use this to align the text fields vertically
txtFields.setLayout(new GridLayout(2, 1));
//Use this for loop to add the labels to this JPanel
for(int i = 0; i < nTextFields; i++)
{
textFields.add(textField[i]);
//You can also define and apply additional properties
//to text fields inside this loop. TIP: You can do
//this in any loop
}
//Now we have the two components, you asked for help with, set up
//Next, we will need another JPanel to add these to panels to.
//This JPanel will be added to the JFrame Container
//You probably know how to run this via the "main" method
JPanel window = new JPanel();
//Place the JPanel for the labels and text fields
//This requires a horizontal grid
window.setLayout(new GridLayout(1, 2));
//Add the the two JPanels: "labels" and "txtFields"
window.add(labels);
window.add(txtFields);
//Define the Container object to set up the GUI
Container container = getContentPane();
//Apply the "window" JPanel object to the container
container.add(window, BorderLayout.CENTER);
//Center this in the Graphics Window when displayed
}
//Any other methods and/or functions can be added as well
//If they are, they must placed in the constructor method above
}
Это подход, который я использовал бы, пытаясь создать и манипулировать моей Графической Windows, которую я пишу. Иногда я пишу апплеты, но только после того, как убедился, что у меня все работает правильно в простом графическом окне.
Надеюсь, это поможет.
Если у вас есть другие вопросы, просто дайте мне знать, и я отвечу на все, что в моих силах, спасибо.