Refreshing JPanel and Switching JTabbedPane in ActionPerfmored - java

private void buttonAddJobActionPerformed(java.awt.event.ActionEvent evt) {
try {
retrieveID();
String sqlStm = "INSERT INTO Job (employerID,title,description,type,salary,benefits,vacancies,closing,requirement,placement,applyTo,status,posted,location) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
pst = conn.prepareStatement(sqlStm);
pst.setInt(1,id);
pst.setString(2,txtTitle.getText());
pst.setString(3,areaDescription.getText());
pst.setString(4,comboType.getSelectedItem().toString());
pst.setString(5,txtSalary.getText());
pst.setString(6,areaBenefits.getText());
pst.setString(7,txtVac.getText());
Date close;
close = txtDate.getDate();
pst.setString(8,sdf.format(close));
pst.setString(9,areaReq.getText());
pst.setString(10,comboPlace.getSelectedItem().toString());
pst.setString(11,txtWeb.getText());
pst.setString(12,comboStatus.getSelectedItem().toString());
Date now = new Date();
pst.setString(13,sdf.format(now));
pst.setString(14,txtLoc.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"You have successfully added a job");
//empty all JTextfields
//switch to another
I am trying to empty the set of JTextFields in the JPanel, but instead of emptying them one by one, can I just refresh the panel? if so, how do you do this. i tried repaint(), revalidate() these dont work. perhaps I am wrong here.
I would also like to switch the JTabbedPane to another Pane, but this doesnt work when I try with this...
JTabbedPane sourceTabbedPane = (JTabbedPane) evt.getSource();
sourceTabbedPane.setSelectedIndex(0);
can someone show an example code how to do this.

You could loop through all components that are contained in the panel, and if they are text components, clear their value. The code would be something like this:
private void clearTextFields(Container container)
{
int count = container.getComponentCount();
for (int i = 0; i < count; i++)
{
Component component = container.getComponent(i);
if (component instanceof Container) {
clearTextFields((Container) component);
}
else if (component instanceof JTextComponent) {
((JTextComponent) component).setText("");
}
}
}
This method works recursively and takes care of the case when your panel contains another panel which contains the text fields.

Keep all your JTextFields in a container, and iterate over that container to empty them.
So, somewhere:
ArrayList<JTextField> textFields = new ArrayList<JTextField>();
After all fields are actually created (with JTextField txtTitle = new JTextField() or similar):
textFields.add(txtTitle);
textFields.add(areaDescription);
// ... add all others here
And finally, when you need to clear them all:
for (JTextField tf : textFields) {
tf.setText("");
}

Related

How to get previous jTabbedPane overlap

I have problem with getting id of previous overlap of jTabbedPane.
ksiegiWieczysteTabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
KsiegaWieczystaPanel księgaWieczystaPanel = (KsiegaWieczystaPanel) ksiegiWieczysteTabbedPane.getSelectedComponent();
if(MainApp.main.showPytanieBox("Czy chcesz zapisać zmiany?")) {
if(księgaWieczystaPanel != null) {
księgaWieczystaPanel.zapiszWszystko();
}
}
}
});
Now I can get the actual clicked overlap but do I have chance to get the previous one? Assume I have 3 overlaps: A,B,C. Now if I click A it is easy to recognize that it is A by ksiegiWieczysteTabbedPane.getSelectedComponent() but when I click B is it possible to know that the previous overlap which was selected were A?
as far as i know this is how to set and get selected index in jtabbedPane
JTabbedPane pane = new JTabbedPane();
// this represents previously selected tab.
int selectedIndex = pane.getSelectedIndex();
//with this method you can change the selected index.
pane.setSelectedIndex(yourIndex);

remove image icon in jbutton

I have a selectpic() method to set images in the jbuttons.
public void selectpic() {
rule rule = new rule();
rule.shuffle();
for (int i = 0; i < 9; i++) {
if (rule.pic[i] == 0) {
Icon0.setImage(Icon0.getImage().getScaledInstance(WIDTH,HEIGHT,Image.SCALE_DEFAULT));
panel1.add(new JButton(Icon0));
} else if (rule.pic[i] == 1) {
Icon1.setImage(Icon1.getImage().getScaledInstance(WIDTH,HEIGHT,Image.SCALE_DEFAULT));
panel1.add(new JButton(Icon1));
} else if (rule.pic[i] == 2) {
Icon2.setImage(Icon2.getImage().getScaledInstance(WIDTH,HEIGHT,Image.SCALE_DEFAULT));
panel1.add(new JButton(Icon2));
} else if (rule.pic[i] == 3) {
Icon3.setImage(Icon3.getImage().getScaledInstance(WIDTH,HEIGHT,Image.SCALE_DEFAULT));
panel1.add(new JButton(Icon3));
} else if (rule.pic[i] == 4) {
Icon4.setImage(Icon4.getImage().getScaledInstance(WIDTH,HEIGHT,Image.SCALE_DEFAULT));
panel1.add(new JButton(Icon4));
} else if (rule.pic[i] == 5) {
Icon5.setImage(Icon5.getImage().getScaledInstance(WIDTH,HEIGHT,Image.SCALE_DEFAULT));
panel1.add(new JButton(Icon5));
}
}
}
When each round is finished i have to call the selectpic() method again to change images.
However, i can't just simply call that method again to do it.
Q1. Is it necessary to remove the images first and then call the selectpic() again, so that it can change the images?
Q2. If so, i searched in forum and found using
xxxx.setImage(null);
can remove the image(xxxx is the name of that jbutton),
but in the selectpic(), i use this to add the jbuttons.
panel1.add(new JButton(Icon0));
how can i know the name of the jbuttons so that i can use xxxx.setImage(null); to remove the images first?
Thanks!!
You're not keeping track of your JButtons, and calling selectpic() fills the JPanel with buttons, so calling it multiple times will create a lot of buttons.
I recommend you to have your JButtons in the class fields, like this:
private JButton button1;
Then, when you initialize your UI, initialize your buttons too:
// UI init here
button1 = new JButton();
panel1.add(button1);
And in the selectpic method, set your icons.
button1.setIcon(choosedIcon);
PD: Now I look more carefully to your code, an array of JButtons would be better, I think. So, the field declaration would be this:
private JButton[] buttons = new JButton[numberOfButtons];
The initalization would be something like this:
for (int i = 0; i < numberOfButtons; i++) {
buttons[i] = new JButton();
panel1.add(buttons[i]);
}
And for setting the icon,
buttons[i].setIcon(chosedIcon);
PD2: I recommend you to start your variable names with a lowercase letter, like in the Naming Convention.

Java how to create several jlists at runtime

I need to create some tabbedpane called "menu" and in each of them I need to put a Jlist (product) with some other data extracted from a mysql db. I created this method but unfortunately it shows only the last jlist, the others menu tabbedpane are empty. Why? Thanks.
for (int i = 0; i < menuLista.size(); i++) {
int menuId = menuLista.get(i).getMenuId();
jProductList = new JList(modelProductList);
prodottiLista.clear();
modelProductList.clear();
prodottiLista = DBManager.fillProductList(menuId);
for (int b = 0; b < prodottiLista.size(); b++) {
modelProductList.addElement((Product) prodottiLista.get(b));
}
jProductList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jProductList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jProductListValueChanged(evt);
}
});
JPanel pL = new JPanel();
pL.add(jScrollPane3);
// panelList.add(pL);
jTabbedPane1.addTab(menuLista.get(i).getMenuName(), pL);
jScrollPane3.setViewportView(jProductList);
}
I've modified the code like this:
for (int i = 0; i < menuLista.size(); i++) {
int menuId = menuLista.get(i).getMenuId();
modelProductList.clear(); // ricarico la lista dei prodotti.
prodottiLista = DBManager.fillProductList(menuId);
for (int b = 0; b < prodottiLista.size(); b++) {
modelProductList.addElement((Product) prodottiLista.get(b));
}
System.out.println(modelProductList);
JScrollPane scrollPane = new JScrollPane(jProductList);
jTabbedPane1.addTab(menuLista.get(i).getMenuName(), scrollPane);
jProductList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jProductList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jProductListValueChanged(evt);
}
});
}
But It still doesn't work as I expected.
EDITED AGAIN:
I noticed that if I put this line:
System.out.println(modelProductList);
after that block of code, it prints exactly only the last products.
So, it's not a problem of visualization. Any suggestion?
jTabbedPane1.addTab(menuLista.get(i).getMenuName(), pL);
jScrollPane3.setViewportView(jProductList);
You add the last JList created to the viewport of the scroll pane. A viewport can only contain a single component.
I would guess you should be adding the tabbed pane to the viewport of the scroll pane. The tabbed pane should be added to the viewport outside of the loop, after all the tabs have been created.
Edit:
Sorry, I misread your code, I see you are adding the list to the scrollpane to a panel to the tabbed pane, so my suggestion is wrong.
However, I was close (I think?). I believe the problem is now with this line:
pL.add(jScrollPane3);
You only have a single instance of the scroll pane, so it can only be displayed on the last tab.
You need to create a new scroll pane for each tab. I would use code like the following:
JScrollPane scrollPane = new JScrollPane( jProductList );
jTabbedPane1.addTab(menuLista.get(i).getMenuName(), scrollPane);
There is no need to add the scroll pane to the panel first. Now the scrollpane will resize as the size of the tabbed pane resizes.
Also, as a side not you should not be using instance variables in your for loop. Instead you should just be using local variables, since these variables will only exist to help you create the GUI objects you add to the tabbed pane.
For example, jProductList, prodottiLista, modelProductList, should all be local variables and you need to create a new instance of each class. You can't just clear() the contents from the model, because each JList will not have a reference to the same model, so again the data that you add to the last tab will be displayed on all tabs.
Ok, I've resolved. This is the working code:
for (int i = 0; i < menuLista.size(); i++) {
int menuId = menuLista.get(i).getMenuId();
DefaultListModel modelProductList = new DefaultListModel();
JList jProductList = new JList(modelProductList);
prodottiLista = DBManager.fillProductList(menuId);
for (int b = 0; b < prodottiLista.size(); b++) {
modelProductList.addElement((Product) prodottiLista.get(b));
}
JScrollPane scrollPane = new JScrollPane(jProductList);
jTabbedPane1.addTab(menuLista.get(i).getMenuName(), scrollPane);
jProductList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jProductListValueChanged(evt);
}
});
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jProductList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}

How do I get input from buttons I created using a loop?

I'm trying to make a simple calculator in Java using Swing, and I've created my buttons the following way:
//Our number keypad
public static JPanel numbers(){
//our panel to return
JPanel panel = new JPanel();
//Create and add 3x4 grid layout to panel
GridLayout gl = new GridLayout(3, 4);
panel.setLayout(gl);
//For creating and adding buttons to panel
for(int i = 0; i < 10; i++){
//Create a new button where the name is the value of i
String name = "" + i + "";
JButton button = new JButton(name);
//add action listener
button.addActionListener(handler);
//Add button to panel
panel.add(button);
}
return panel;
}
My question is how do I reference each specific button in my event handler? I can't think of a way to do this without having to manually create each button rather than using a loop.
Thanks.
In your listener, call event.getSource(), and that will return the button which has been pressed. Get the text of the button, and you have its number.
Or create a different instance of your handler for every button, and pass the value of the button (i) to the constructor of the handler. This last solution is cleaner, IMO, because it doesn't depend on the text of the button. If you replaced the text by an image, for example, the first technique wouldn't work anymore.
You can distinguish created buttons by adding the following inside handler:
String buttonText = ((JButton) e.getSource()).getText();
if (<text1>.equals(buttonText)){
//do the stuff
} else if (<text2>.equals(buttonText)){
//do the stuff
} else {
//do the stuff
}
Method #1: go through the child components of the parent JPanel (quite tedious, has to be rebuilt every time you modify the contents of that JPanel). Make sure they're JButtons by using an if . . instanceof clause.
Method #2: as you create them in that loop, add them to a List (or even better, a Map). I prefer a Map personally as it lets me customise the key for that specific JComponent
i.e.
HashMap<String, JComponent> buttonList = new HashMap<String, JComponent>();
for(. .) {
buttonList.put("nameForEachButton", button);
}
I recommend generating the button name based off of the loop counter. Either use your existing name value, or just set it to "button" + i;
Declare your buttons using an array.
JButton[] button = new JButton[9]; //outside the for loop
for (int i = 0; i < 10; i++) {
//put your code
button[i] = new JButton(name);
//your code
}

Use arrayList to display in JTextArea

I want to be able to display all items in an arrayList in a JTextArea. This is the code I have but it does not work.
public void display()
{
JPanel display = new JPanel();
display.setVisible(true);
JTextArea a;
for (Shape ashape : alist)
{
System.out.println("");
System.out.println(ashape.toString());
a = new JTextArea(ashape.toString());
display.add(a);
}
Container content = getContentPane();
content.add(display);
}
Move
JTextArea a;
inside for loop, like so:
for (Shape ashape : alist) {
System.out.println("");
System.out.println(ashape.toString());
//initialise a here
JTextArea a = new JTextArea(ashape.toString());
display.add(a);
}
Container content = getContentPane();
content.add(display);
}
Also, what does it mean "it doesn't work" in your program?
There are a couple of ways to achieve this. To start with, your example code is creating a new JTextArea for each Shape, but it is only ever adding the last to the UI.
Assuming you want to display all the information in a single text area, you could simply use JTextArea#append, for example
JTextArea a = new JTextArea();
for (Shape ashape : a list)
{
System.out.println(ashape.toString());
a.append(ashape.toString() + "\n")
}
Container content = getContentPane();
content.add(display);
Ps- you may want to wrap the text area within a JScrollPane so it can overflow

Categories

Resources