I want to do a dynamic form in Swing. When I call firstly the dataShow method, it creates the GUI. But when I call it again, it keeps the old panel and display the new at the background.
And when I try to remove the current panel, and then add the new. The GUI became empty
A Thread listen to events (int id in that case).
here is my code to display the dynamic form :
public void showData(int id) throws DAOException, ClassNotFoundException{
FormDAOImpl form = new FormDAOImpl();
String b = form.importTagPoint(id);
//if(compteur%2 == 0) {System.out.println("Compteur : " +compteur); scrollPane.remove(panel);
//frame.getContentPane().remove(scrollPane);
//}
panel = new JPanel(new MigLayout());
if(b == null) b = "";
String[] bits = b.split("\\,");
String delims = "[=]";
while(i<bits.length){
textField = new JTextField();
String[] bitsS = bits[i].split(delims);
textField.setText(bitsS[1]);
JLabel label = new JLabel(bitsS[0]+ " : ");
panel.add(label);
panel.add(textField, "span, grow, alignx center, flowx");
i++;
}
JButton annuler = new JButton("Annuler");
JButton enregistrer = new JButton("Enregistrer");
panel.add(annuler);
panel.add(enregistrer);
panel.revalidate();
panel.repaint();
scrollPane = new JScrollPane(panel);
scrollPane.revalidate();
scrollPane.repaint();
frame.getContentPane().add(scrollPane);
//frame.repaint();
frame.invalidate();
frame.validate();
frame.repaint();
frame.pack();
frame.setMaximumSize(new Dimension(300, 800));
compteur++;
}
First, try calling frame.getContentPane().removeAll() to remove anything that was previously added to it. Obviously do this before you add anything new to it.
Second, try and devise a solution where you don't need to do this, but maintain a single view which can be updated via setters and getters if possible.
If you are literally changing views (show the user something complete different), consider using a CardLayout or JTabbedPane instead
Related
Here is part of my code:
JFrame window = new JFrame();
JPanel panel = new JPanel();
JTextArea text = new JTextArea();
JScrollPane scroll = new JScrollPane(text);
private Window()
{
createWindow();
}
public void createWindow()
{
window.setLayout(null);
window.setVisible(true);
panel.setVisible(true);
text.setBounds(20, 100, 320, 270);
}
public void update2(String employee)
{
text.setText(null);
try
{
scanner = new Scanner(employee);
}catch(Exception e){
e.printStackTrace();
}
while(scanner.hasNextLine())
{
String line = scanner.nextLine();
text.append(line+"\n");
}
revalidate();
}
I'm wondering how to add scroll bar to TextArea "text". It's a database app and it sends String of data to TextArea. I want the app to show scrollbar (vertical or horizontal) if necessary - too many Strings in TextArea. I have been trying many things but nothing works. Constructor has to be private because I'm using Singleton.
Avoid using null layouts. Take a look at Layout Managers for better options.
Unless you are not including the part where you add the Scrollpane to the JFrame, I suggest you do something similar to this
frame.add(scrollpane, BorderLayout.CENTER);
The BorderLayout.CENTER is a position in the default layout for JFrames. Read here for more.
Btw, where did you add your scroll to the Frame?
window.add(scroll);
window.setVisible (true);
JScrollPane is a container that places scrollbars around your component when its needed and also has its own layout. All you need to do when you want to wrap anything into a scroll just pass it into JScrollPane constructor:.
JFrame window = new JFrame();
JPanel panel = new JPanel();
JTextArea text = new JTextArea();
JScrollPane scroll = new JScrollPane(text);
If the above did not work, use:
JScrollPane scroll = new JScrollPane ();
scroll.getViewport ().setView ( text );
I have a JTable which contains a list of item and a JPanel with some components. When I click to my button, I want all information of the selected item in the JTable will be loaded to the JPanel. At the first time, it work well but at the further times when I click to my button the Jpanel appears with empty component.
The code when clicking to my button:
jbtUpdateContract.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
Object contractID = getValueOfSelectedRow(contractTable, 0);
Contract contract = contractTransaction.getContractByID(Integer.parseInt(contractID.toString()));
//Create Jpanel to display information
jplUpdateContractForm.removeAll();
jplUpdateContractForm = createContractForm(contract);
jplUpdateContractForm.revalidate();
//Modify contract frame
jfrmUpdateContract.getContentPane().add(jplUpdateContractForm,
BorderLayout.CENTER);
jfrmUpdateContract.setSize(400, 300);
jfrmUpdateContract.setVisible(true);
jfrmUpdateContract.setResizable(false);
}
});
And my createContractForm function:
public static JPanel createContractForm(Contract contract)
{
JPanel jplContractForm = new JPanel(new SpringLayout());
JLabel jlblAppointmentDate = new JLabel("Appointment date:", JLabel.TRAILING);
jlblAppointmentDate.setName("jlblAppointmentDate");
jplContractForm.add(jlblAppointmentDate);
final JTextField jtxtAppointmentDate = new JTextField(15);
jtxtAppointmentDate.setName("jtxtAppointmentDate");
jtxtAppointmentDate.setText(contract.getAppointmentDate());
jtxtAppointmentDate.setEditable(false);
jtxtAppointmentDate.addMouseListener(appointmentDateMouseListener(jtxtAppointmentDate));
jlblAppointmentDate.setLabelFor(jtxtAppointmentDate);
jplContractForm.add(jtxtAppointmentDate);
jplContractForm.setOpaque(true);
//***Customer Cobobox
JLabel jlblCustomer= new JLabel("Customer:", JLabel.TRAILING);
jlblCustomer.setName("jlblCustomer");
jplContractForm.add(jlblCustomer);
final JComboBox jcbxCustomer = new JComboBox();
jcbxCustomer.setName("jcbxCustomer");
//Load customers from DB to combobox
Customer[] customers = customerTransaction.getAllCustomer();
for(int i = 0; i < customers.length; i++)
jcbxCustomer.addItem(customers[i]);
System.out.println("----------CUSTOMER----------" + getIndexOfCustomerComboBoxItem(jcbxCustomer, contract.getCustomerSeq()));
jcbxCustomer.setSelectedIndex(getIndexOfCustomerComboBoxItem(jcbxCustomer, contract.getCustomerSeq()));
jlblCustomer.setLabelFor(jcbxCustomer);
jplContractForm.add(jcbxCustomer);
jplContractForm.setOpaque(true);
}
Please help me to explaint why the JPanel is empty as I describes above.
Regards.
The frame is already visible, so I don't think any of these lines of code will help.
jfrmUpdateContract.setSize(400, 300);
jfrmUpdateContract.setVisible(true);
jfrmUpdateContract.setResizable(false);
The revalidate() does nothing because you haven't added the panel to the frame yet. Try the revalidate() AFTER the panel has been added to the frame.
jplUpdateContractForm = createContractForm(contract);
//jplUpdateContractForm.revalidate();
jfrmUpdateContract.getContentPane().add(jplUpdateContractForm, BorderLayout.CENTER);
jplUpdateContractForm.revalidate();
If you need more help then post a proper SSCCE.
I have one JFrame with two Buttons in East and West,Label in North,Label and TextField in South. and one Image in the Center. I want to call another Image after 30 seconds in the center. But every time I call the 2nd image the components in North,South,East and West are disappearing.
This is my code.
//The Components in JFrame.
firstPicblur = new JPanel(new BorderLayout());
pictureblur01 = new ImageIcon("C:\\java pics\\papsi2.jpg");
pictureblurA = new JLabel(pictureblur01);
firstPicblur.add(pictureblurA,BorderLayout.CENTER);
//FirstPicture blurred B
firstPicblurB = new JPanel(new BorderLayout());
pictureblur02 = new ImageIcon("C:\\java pics\\papsi1.jpg");
pictureblurB = new JLabel(pictureblur02);
firstPicblurB.add(pictureblurB,BorderLayout.CENTER);
//Next0Prev buttons
Next0Prev = new JPanel(new BorderLayout());
Next = new JButton("NEXT");
Prev = new JButton("PREV");
//Next0Prev labels is constant at SOUTH
firstPicblurA = new JPanel(new BorderLayout());
clueNo1 = new JLabel("Picture Number 01");
TypeHere = new JTextField("Guess Who");
firstPicblurA.add(TypeHere, BorderLayout.CENTER);
firstPicblurA.add(clueNo1, BorderLayout.SOUTH);
Next0Prev.add(firstPicblur,BorderLayout.CENTER);
Next0Prev.add(Next,BorderLayout.EAST);
Next0Prev.add(Prev,BorderLayout.WEST);
Next0Prev.add(firstPicblurA,BorderLayout.SOUTH);
//other components
and this is the actionEvent
if(e.getSource() == continueButton){
add(Next0Prev);
Next0Prev.setVisible(true);
Next0Prev.repaint();
Next0Prev.revalidate();
loadingEffectBtn.setVisible(false);
Timer ta = new Timer(10000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
add(firstPicblurB);
firstPicblurB.setVisible(true);
Next0Prev.setVisible(true);
}
});
ta.start();
ta.setRepeats(true);
}
but when i do this. The 2nd picture is appearing in center but the N,E,W,S components are disappearing.
This is a bit hard to tell, but what appears to be happening is...
You're creating Next0Prev and adding all your components to it...
Next0Prev = new JPanel(new BorderLayout());
//....
Next0Prev.add(firstPicblur,BorderLayout.CENTER);
Next0Prev.add(Next,BorderLayout.EAST);
Next0Prev.add(Prev,BorderLayout.WEST);
Next0Prev.add(firstPicblurA,BorderLayout.SOUTH);
Which I assume you are adding to the frame...
Then in your Timer's actionPerformed, you're adding firstPicblurB to the main container...
public void actionPerformed(ActionEvent e) {
add(firstPicblurB);
firstPicblurB.setVisible(true);
Next0Prev.setVisible(true);
}
Now, assuming that the main container is either a JFrame or is using a BorderLayout, this will effectively hide Next0Prev as BorderLayout can only have a single component in any of it's 5 positions.
Instead, you should be adding firstPicblurB to Next0Prev...
A simpler solution would be (as has already being pointed out) to use a single JLabel and simple change it's icon
I would also highly recommend that you take the time to read through and apply Code Conventions for the Java Programming Language
String result = JOptionPane.showInputDialog(this, temp);
result value will be the inputted value.
String result = JOptionPane.showInternalInputDialog(this, temp);
result value will be null even you inputted a string.
temp is a panel that will contain in the JOptionPane. This JOptionPane will show on top of another customized JOptioPane.
JOptionPane.showInternalInputDialog is to be used with JDesktopPane/JInternalFrames only, where this is the JDesktopPane/JInternalFrames instance.
final JDesktopPane desk = new JDesktopPane();
...
String s=JOptionPane.showInternalInputDialog(desk, "Enter Name");
If not used with either of the 2 above mentioned components it will not produce the correct output, in fact it will throw a Runtime Exception:
java.lang.RuntimeException: JOptionPane: parentComponent does not have
a valid parent
UPDATE
As per your comments here is an example of how you would add JPanel to JDesktopPane and call JOptionPane#showInternalInputDialog. The important part is we need to call setBounds and setVisible on JPanel like we would as if it was JInternalFrame being added to the JDesktopPane, except of course we are adding a JPanel
JFrame frame = new JFrame("JInternalFrame Usage Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// A specialized layered pane to be used with JInternalFrames
jdpDesktop = new JDesktopPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
};
frame.setContentPane(jdpDesktop);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 600, 600);
jdpDesktop.add(panel);
frame.pack();
frame.setVisible(true);
panel.setVisible(true);
String result = JOptionPane.showInternalInputDialog(jdpDesktop, "h");
System.out.println(result);
I want to repeatedly take input from the user(probably using a button) via a JOptionPane(already done) and store the details in something(how about a dynamic object array) and display this information as a list in a scrollable JList.
MY CODE
import java.awt.GridLayout;
import javax.swing.*;
class Flight {
public static void main(String[] args) {
//Panel
JPanel panel = new JPanel(new GridLayout(7, 2,20, 20));
//Add textfields here
JTextField txtflightno = new JTextField(8);
JTextField txtmechanicalstatus = new JTextField(8);
JTextField txtmedicalstatus = new JTextField(8);
JTextField txtfuellevel = new JTextField(8);
JTextField txtweathercondition = new JTextField(8);
JTextField txtfrequency = new JTextField(8);
JTextField txtflightpath = new JTextField(8);
//Add labels here
JLabel lblflightno = new JLabel("Flight No : ");
JLabel lblmechanicalstatus = new JLabel("Mechanical Status:");
JLabel lblmedicalstatus = new JLabel("Medical Status:");
JLabel lblfuellevel = new JLabel("Fuel Level:");
JLabel lblweathercondition = new JLabel("Weather Condition:");
JLabel lblfrequency = new JLabel("Frequency:");
JLabel lblflightpath = new JLabel("Flight Path:");
//Adding flightno to panel
panel.add(lblflightno);
panel.add(txtflightno);
//Adding mechanicalstatus to the panel
panel.add(lblmechanicalstatus);
panel.add(txtmechanicalstatus);
//Adding medicalstatus to the panel
panel.add(lblmedicalstatus);
panel.add(txtmedicalstatus);
//Adding fuellevel to the panel
panel.add(lblfuellevel);
panel.add(txtfuellevel);
//Adding weathercondition to the panel
panel.add(lblweathercondition);
panel.add(txtweathercondition);
//Adding frequency to the panel
panel.add(lblfrequency);
panel.add(txtfrequency);
//Adding flightpath to the panel
panel.add(lblflightpath);
panel.add(txtflightpath);
panel.setBounds(0, 0, 800, 600);
int result = JOptionPane.showConfirmDialog(null, panel, "Flight Details",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
}
}
}
How must I do the storing of the plane details ? How must I implement a scrollable JList ? Any suggestions.
Many Thanks
As discussed in How to Use Lists, JList uses a list model as the source of data it displays. Just add your data to a DefaultListModel, and use it to construct your list.
DefaultListModel dlm = new DefaultListModel();
// add data
JList list = new JList(dlm);
panel.add(new JScrollPane(list));
To make the JList scrollable, simply embed it in a JScrollPane. Instead of
add(myList, constraints);
do
add(new JScrollPane(myList), constraints);
To extend the list, just get the JList's ListModel (using getListModel) and use add to add objects.
More on using ListModels in Sun's tutorial.
More on ScrollPane in the Tutorial, too.
You've to use the ActionListener of Button, that you've missed in the code snippet.
In the OK Option :
JList jlist = ...;
jlist.add(txtflightno.getText());
jlist.add(txtmechanicalstatus.getText());
jlist.add(txtmedicalstatus.getText());
....
....
&
add(new JScrollPanel(myList), constraints);
After this use validate method of Component to update the list with this new item.
But one thing you should remember is that list displays each item row-wise.
I suggest you to use JTable with which you can display your items in a meaningful way...