Update JPanel in JDialog
Hey,
need some help please....
I've searched long and hard but can't find anything.
I've got an application that opens a JDialog, then jDialog has a JPanel within
it.
Once the JDialog has loaded on the screen i want to update the Jpanel based on
a button click.
My problem is that the JPanel wont update.
I've made a simple program that displays the same behaviour.
Frame with a button on it to open a JDialog :
public class testFrame extends javax.swing.JFrame {
/** Creates new form testFrame */
public testFrame() {
initComponents();
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Show Dialog");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(150, 150, 150)
.addComponent(jButton1)
.addContainerGap(159, Short.MAX_VALUE))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(135, 135, 135)
.addComponent(jButton1)
.addContainerGap(142, Short.MAX_VALUE))
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
testJDialog test = new testJDialog(this,true);
test.setVisible(true);
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new testFrame().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}JDialog code :
import javax.swing.JTree;
* @author wesley
public class testJDialog extends javax.swing.JDialog {
/** Creates new form testJDialog */
public testJDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("TitleBorder"));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 347, Short.MAX_VALUE)
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 128, Short.MAX_VALUE)
jButton1.setText("Add Tree");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(145, 145, 145)
.addComponent(jButton1)))
.addContainerGap(31, Short.MAX_VALUE))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.jPanel1.add(new JTree());
this.pack();
this.repaint();
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
testJDialog dialog = new testJDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
dialog.setVisible(true);
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}Ive tried
this.pack();
this.repaint();but i cant get the JPanel to repaint.
Im using Vista Java version
C:\Users\wesley>java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)Cheers
Wesley
wesleyelder wrote:
Thanks so much for taking the time to reply, that worked a treat.you're welcome
i agree the netbeans code is a mess sometimes but when i just need a simple JDialog i sometimes use it, just lazy a guess :)But then you run into problems like this one. I'd much prefer to make my own simple JDialog:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
public class TestMyDialog
private JPanel mainPanel = new JPanel();
private JPanel centerPanel = new JPanel();
public TestMyDialog()
JButton addTreeBtn = new JButton("Add Tree");
addTreeBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
addTreeAction();
JPanel buttonPanel = new JPanel();
buttonPanel.add(addTreeBtn);
centerPanel.setBorder(BorderFactory.createTitledBorder("Title Border"));
centerPanel.setPreferredSize(new Dimension(400, 200));
centerPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
mainPanel.setLayout(new BorderLayout(20, 20));
mainPanel.add(centerPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
private void addTreeAction()
JTree tree = new JTree();
tree.setOpaque(false);
centerPanel.add(new JScrollPane(tree), BorderLayout.CENTER);
centerPanel.revalidate();
public JPanel getMainPanel()
return mainPanel;
private static void createAndShowUI()
final JFrame frame = new JFrame("Test My Dialog");
JPanel framePanel = new JPanel();
framePanel.setBorder(BorderFactory.createEmptyBorder(200, 200, 200, 200));
framePanel.setPreferredSize(new Dimension(500, 500));
JButton showDialogBtn = new JButton("Show Dialog");
showDialogBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
showDialogAction(frame);
framePanel.add(showDialogBtn);
frame.getContentPane().add(framePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
private static void showDialogAction(JFrame frame)
JDialog dialog = new JDialog(frame, "My Dialog", true);
dialog.getContentPane().add(new TestMyDialog().getMainPanel());
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
public static void main(String[] args)
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
createAndShowUI();
}
Similar Messages
-
Unable to update JComboBox in JDialog
Method configureShiftList() updates the contents of a JComboBox in one of my JDialogs however when the JDialog is then displayed the updated contents of the JComboBox are not displayed. Thoughts on how to change this?
public class addButton3Handler implements ActionListener {
public void actionPerformed( ActionEvent e) {
configureShiftList();
addList3Dialog.validate();
addList3Dialog.setVisible(true);
}Have you made sure that the container of this
component is also validated. If the container is not
validated, then the change that you've made here would
not have shown up.
V.V.Isn't the JDialog the container or are you saying I need to also validate the parent JPanel and/or its parent JFrame?
Thanks,
Vaughn -
Use JWindow, JInternalFrame, JPanel, or JDialog
Hello,
My main window application extends a JFrame. When a component of the JFrame is mouse clicked,I want to open a popup window on top of this frame.
The opened window is used to receive input from the user; with these properties: title bar, resizeable, can close with the "X" on the right side of the title bar, no minimizable or maximizable buttons on the title bar.
1. I am very unsure whether I should use: a JWindow, JInternalFrame, JPanel, JDialog, JPopupMenu (probably not since I don't need a menu) to create the popup window. I think I should use JWindow, but am not sure.
2. Also, I am unsure whether I can use JWindow and JInternalFrame with JFrame as the main app window.
Thank you for your advice.If you want a popup window on top of this frame, you can either choose JFrame, JDialog or JWindow. They all have the own characteristics.
JFrame: Usually application will use it as the base. Because It has a title bar with minimizable, maximizable and exit button.
JDialog: Usually work as a option / peference / about dialog (Ex. Just click the IE about to see). Because it has a smaller title bar with only maximizable and exit button and the model setting. If model is to TRUE, that means all the other area of the window will be disable except the opened dialog own.
JWindow: Usually use as a splash to display logo or welcome message.
JInternalFrame: It display inside a desktop panel of JFrame. Just like the multi-documents function inside the MS Words. -
Updating JPanel during a loop.
Here's the deal: my first class (first file) which extends a JFrame, creates a JFrame and adds some JPanels to it (with buttons, JTextFields etc), after i press one button it creates an instance of a class Algorithm that is in another file, and calls a function solve() from that class, which counts some things. In that function (the start() one) there are 2 loops, and it returns a stack. The thing is I want a JTextField from that JFrame to be updated with every new loop (so it would show numbers 1,2,3,4,etc while the function was being executed). If they were in a single file than there would be no problem (simply message.setText(loopNumber+"");), but since they are in different files I have no idea how to do it. Should I try making a new thread for the solve() function or what?
It would be something like this, file1 (tho the new Algorithm part isnt in main() but it is executed after a button is pressed):
public class Frame extends JFrame{
variables
private JTextField message; // this one is in one of the JPanels attached to the JFrame
main(){
JFrame frame = new JFrame();
new algorithm = new Algorithm(passes some variables);
algorithm.solve();
}Second file:
public class Algorithm{
some variables,
constructor etc;
int numer = 0;
public void solve(){
for(int i=0; i < 10; i++){
numer += 1;
something happens here;
}And I want to change the "message" whenever "number" changes.Someone told me I should make a new thread for the soultion() in order to "repaint" the JPanel that contains the "message"...Not for setting a text field, you shouldn't. But you're getting dangerously close to mashing up your GUI and "business" logic with inappropriate relationships. You may want to have a look at the Observer pattern, where your algorithm can notify any observers of state changes, and the observers can handle that information as they see fit.
~ -
Updating JPanel with buttons from a different class
I have a JPanel in a class that has a gridlayout with buttons in it for a game board. And my problem is that when I want to update a button using setIcon() the button doesn't change in the GUI because the buttons are in a different class. The JPanel is in a Client class and the buttons are in a GamePlugin class. I've tried a bunch of different things but none of them worked or it was way too slow. I'm sure theres an easy way to do it that I'm not seeing. Any suggestions? Heres part of my code for updating the GUI.
private JPanel boardPanel = new JPanel();
Container cP = getContentPane();
cP.add(boardPanel, BorderLayout.WEST);
boardPanel.setPreferredSize(new Dimension(400, 400));
boardPanel.setLayout(new GridLayout(8, 8));
cP.add(optionsPanel, BorderLayout.CENTER);
* Gets the board panel from the selected plugin.
public void drawGameBoard(GamePlugin plugin) {
board = (OthelloPlugin)plugin;
boardPanel = board.getBoardPanel();
for (int i = 0; i < GamePlugin.BOARD_SIZE; i++)
for (int j = 0; j < GamePlugin.BOARD_SIZE; j++) {
board.boardButtons[i][j].setActionCommand("" + i + "" + j);
board.boardButtons[i][j].addActionListener(this);
* This method takes a GameBoard and uses it to update this class' data
* and GUI representation of the board.
public void updateBoard(GamePlugin updatedBoard) {
board = (OthelloPlugin)updatedBoard;
for (int i = 0; i < GamePlugin.BOARD_SIZE; i++) {
for (int j = 0; j < GamePlugin.BOARD_SIZE; j++) {
int cell = board.getCell(i,j);
if (cell == OthelloPlugin.PLAYER1){
board.boardButtons[i][j].setIcon(black);
else if (cell == OthelloPlugin.PLAYER2)
board.boardButtons[i][j].setIcon(white);
else
board.boardButtons[i][j].setText("");
}txp200:
I agree that a call to validate() , possibly repaint(), should fix your problem. In the class with the panel that the buttons are on, i would create a static repaint method that call panel.repaint(). You can then call that method in your other class. Just make sure u only use methods to change the properties of the button, never make a make a new one, as then you will lose the association with the panel. Hope this helps.
-- Brady E -
Theory: Displaying JPanels in JDialogs
Hi all,
I went ahead and developed my classes as JPanels, as I thought it would be more extensible than if I made them JDialogs directly.
But I didn't think it through. Now when I want to add them to a JDialog, I need to make the JDialog inside the class, so the class can call dispose on it (I actually call setVisible(false)... is one way better than the other?).
This isn't really a hassle, though it defeats the point of making my class a JPanel. What's the accepted practice here? Do people make classes as JPanels, then add them to things? Is there a better way of doing this?
Would I be better off just making my class extend JDialog and do away with the JPanel? (although I'm aiming for extensibility, it's really all theoretical as I can't envision myself or anyone else reusing these classes).
Just want to know way most people do it.
Cheers,
Radish21Ok, that works for my app. But is this a publicy accepted way of doing things?
Before I get too far, I just want to make sure I'm not doing things ass-about. -
Hi everyone!
I have the following problem:
My application makes it possible to watch the movement of a few balls simultaniously. The problem is that every ball updates the panel after it draws itself. This makes great mess when the balls are more than one. Can you help me?
Thanks in advance!Sounds like control design problem. You might try something like...
Have each ball move in it's own thread. Set up a SwingUtilities.Timer to repaint all the balls at a given time interval, say 1/30th of a second, or whatever you can smoothly support on your hardware. Alternatively, you could have the timer update the position of the balls before it draws them. The right answer depends on your system and requirements.
Happy balling! -
I'm wondering which methord I am supposed to override if I need to add extra features when a JPanel needs to be refreshed. Right now, I am overriding the updateUI() methord. Is this the right way to do it, or is there some more efficient methord?
What do you mean by "add extra features"? Most of the time, you want to override the paintComponent method to control painting, and you add mouse or key listeners to handle input. Please clarify more on what you want to do.
-JBoeing -
Hi.
I'm writing a software with one frame and in its contentPane in made up with two JPanel which changes continuously. The problem is that when I close that main frame the whole computer stops and seemes to enter into deadlock.
Can someone tell me which is the best method to close frames, dialogs and panels (I think it's the reason for my problem).
Now I'm using setVisible for panels and dialogs.
ThanksTry something like :-
public class MyFrame
extends JFrame
public MyFrame()
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent wndwEvnt)
dispose();
System.exit(0);
}There are other constants (e.g. WindowConstants.DISPOSE_ON_CLOSE if memory serves), that you can use depending on what you want to do when you 'close'. -
ProcesskeyEvent not invoked in JDialog andin JPanel
I have overriden processKeyEvent in my class but this method never gets invoked on typing or pressing
a key but the processMouseEvents are invoked properly the JDK Version which I am using is
1.4.1_01 .Please guide what else should be done to handle key events for JDialog or Jpanel
import java.awt.*;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
public class TestDialog extends JDialog {
public TestDialog(){
this.getContentPane().setLayout(null);
JButton jb = new JButton("HJHJH");
jb.setBounds(10,10,100,30);
this.getContentPane().add(jb);
this.enableEvents(AWTEvent.KEY_EVENT_MASK |AWTEvent.MOUSE_EVENT_MASK);
setSize(300,300);
setVisible(true);
public void processKeyEvent(KeyEvent keyEvent){
System.out.println("Key Event Called");
public void processMouseEvent(MouseEvent mouseEvent){
System.out.println("Mouse Event Called");
public static void main(String args[]){
new TestDialog();Hi
Any component is passed events through processXXX() methods only if the component has focus.
Components like JPanel and JDialog never gain focus as the focus manager in java does not define focuses for a panel or JDialog . instead interactive comp.s like JButton , JTextField have focuses.
Override the setVisible(boolean) method as
public void setVisible(boolean b)
super.setVisible(b);
mycomp.grabFocus();
After this do not click the mouse anywhere else , if clicked the focus will again be lost.
try pressing keys and u'll know why it was happening.
Have fun..
Fire an reply trying this.
RGDS -
Hello Frnds,
my problem is quite weird!! i will try to explain..as much as I can !!
My requirement is I want to show same JPanel in JDialog and JFrame at once..!!
I am adding a
JPanel A ---> JDialog
JPanel A ---> JScrollPanel B
JScrollPane B ---> JFrame.. and making frame and dialog visible together.. but JPanel is visible in dialog only..
if i dont add in JDialog.. then JPanel is visible in frame.. !!.. but why that??
JFrame fr = new JFrame();
JPanel np = new JPanel(); // This JPanel is added Twice
np.setBounds(0, 0, 128, 128);
JScrollPane scroll=new JScrollPane(np); // Once JPanel added here..
scroll.setPreferredSize(new Dimension(385,385));
fr.add(scroll);
JDialog dlg=new JDialog(fr, "Another Panel", false);
dlg.add(np); // Second Time JPanel added here..
dlg.pack();
dlg.setVisible(true);
fr.setVisible(true);Let's make it very clear : it is NOT possible to add
the same instance of a component to two different
containers.
Is it possible to have frame with component.. but on closing that frame component shifts to another frame.. and vice versa I will add to the above:
it is NOT possible to add the same instance of a component to two different containers... at the same time. Does that clarify it?
Why is it so hard to try it yourself?
Instead of waiting a couple of hours hoping someone answers the question you could have solved your problem in a couple of minutes. -
Hello!
i have created a JDialog that has a JPanel. this JPanel has a list that's frequently updated.
Now, when i first started coding, i used J2RE 1.4.2 ----->The JDialog and its JPanel worked perfectly!!!
I switched to JDK 1.5 and there were problems!!!
here is my code that worked with J2RE 1.4.2, why doesn't it work with JDK 1.5??
private JPanel listPanel = new JPanel();...
private void createJDialogBox()
boxDialog = new JDialog();
boxDialog.getContentPane().setLayout(new BorderLayout());
boxDialog.addWindowListener(this);
dialogCancelButton = new JButton();
dialogCancelButton.setFont(new Font(constVar.getButtonFont(), constVar.getButtonFontStyle(), constVar.getButtonFontSize()));
dialogOkButton = new JButton();
dialogOkButton.setFont(new Font(constVar.getButtonFont(), constVar.getButtonFontStyle(), constVar.getButtonFontSize()));
goToPanel = new JPanel();
goToPanel.setLayout(new BorderLayout());
goToPanel.setPreferredSize(new java.awt.Dimension(149, 31));
titlePanel = new JPanel();
titlePanel.setBorder(new EtchedBorder());
goToLabel = new JLabel();
goToLabel.setFont(new Font(constVar.getLabelFont(), constVar.getLabelFontStyle(), constVar.getLabelFontSize()));
goToLabel.setHorizontalAlignment(SwingConstants.CENTER);
goToTextField = new JTextField();
goToTextField.setPreferredSize(new java.awt.Dimension(10, 20));
goToTextField.setFont(new Font(constVar.getTextFieldFont(), constVar.getTextFieldFontStyle(), constVar.getTextFieldFontSize()));
southPanel = new JPanel(new GridLayout(2, 2));
// pour le label de Go To
goToString = anAction.getLabel(languageNumber, "BD_GO_TO");
// pour le label de Cancel
dialogCancelButton.setText(anAction.getLabel(languageNumber, "CANCEL"));
// pour le label de Ok
dialogOkButton.setText(anAction.getLabel(languageNumber, "OK"));
goToLabel.setText(goToString);
southPanel.add(goToLabel);
southPanel.add(goToTextField);
dialogOkButton.addMouseListener(new MouseAdapter()
public void mouseClicked(MouseEvent evt)
dialogOkButtonMouseClicked(evt);
dialogCancelButton.addMouseListener(new MouseAdapter()
public void mouseClicked(MouseEvent evt)
dialogCancelButtonMouseClicked(evt, boxDialog);
southPanel.add(dialogOkButton);
southPanel.add(dialogCancelButton);
boxDialog.getContentPane().add(southPanel, BorderLayout.SOUTH);
boxDialog.setSize(new Dimension(500,300));
boxDialog.setLocationRelativeTo(generalPanel);
//somewhere in the constructor i call createJDialogBox();...
//this is where i update the JPanel with a specific list
//the other functions that share the same JDialog have the same implementation: a list is created and added to the JPanel
public void mpnItemActionPerformed(Connection conn, ActionEvent e, int languageNumber, JPanel generalPanel, JPanel listPanel, JDialog boxDialog, List mpnSearchList)
int product = getProductNumber();
setLanguageNumber(languageNumber);
try
if (product == -1)// on n'a pas selectionne de produit particulier, donc on affiche tout
stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet result = stat.executeQuery("Select SQL From ICM_SQL Where ID = 55");
while (result.next())
sql = result.getString("SQL");
result = stat.executeQuery(sql);
while (result.next())
String item = "", firstMPN = "", secondMPN = "";
firstMPN = result.getString(1);
secondMPN = result.getString(2);
if (firstMPN.compareTo(secondMPN) == 0) // si les 2 sont
// pareils, n'afficher
// que le 1er
item = item + firstMPN;
else
// afficher le 2eme
item = item + secondMPN;
mpnSearchList.add(item); // remplir la liste
else
stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String[] variablesArray = new String[2];
variablesArray[0] = "" + product;
variablesArray[1] = "" + product;
ResultSet result = stat.executeQuery("Select SQL From ICM_SQL Where ID = 12");
while (result.next())
sql = result.getString("SQL");
sql = addVariables(sql, variablesArray);
result = stat.executeQuery(sql);
while (result.next())
String item = "", firstMPN = "", secondMPN = "";
firstMPN = result.getString(1);
secondMPN = result.getString(2);
if (firstMPN.compareTo(secondMPN) == 0) // si les 2 sont
// pareils, n'afficher
// que le 1er
item = item + firstMPN;
else
// afficher le 2eme
item = item + secondMPN;
mpnSearchList.add(item); // remplir la liste
for(int i =0;i<mpnSearchList.getItemCount();i++)
System.out.println(mpnSearchList.getItem(i));
listPanel = new JPanel();
listPanel.setLayout(new BorderLayout());
mpnSearchList.setFont(new java.awt.Font("Arial", 0, 12));
listPanel.add(mpnSearchList, BorderLayout.CENTER);
boxDialog.getContentPane().add(listPanel, BorderLayout.CENTER);
} catch(SQLException exc)
System.out.println("Error in mpnItemActionPerformed - SQL Exception");
//boxDialog.setModal(true);
boxDialog.setVisible(true);
} please help me.
ThanksInstead of creating a new JList all the time. Just change data in the existing list. Something like:
ListModel model = new DefaultListModel(....);
list.setModel( model ); -
helloo..
i have a java application that will add records , search and update records in the database..
i have the fields id,name,phone,address,sex and dob..
i will be having an update button , whenever the user will click on the update button he can update the record he wants and then the updated record will be stored..but i don't know how to write the code for this ..
can any one help me by giving me a sample code...
this is my application code:
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class Insert3 extends JFrame implements ActionListener
JTextField id, name,address,phone,sex,dob;
JButton add,update;
JPanel panel, buttonPanel;
static ResultSet res;
static Connection conn;
static Statement stat;
static String[][] tableData;
JTable dataTable;
Container c = getContentPane();
JScrollPane scrollpane;
//private ImageIcon logo;
public static void main (String[] args)
Insert3 worker = new Insert3();
try
//Connect to the database and insert some records:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:database");//database is the DSName
stat = conn.createStatement();
/*stat.executeUpdate("INSERT INTO Customer VALUES (1001, 'Simpson','hamad town',222,'m','may 72')");
stat.executeUpdate("INSERT INTO Customer VALUES (1002, 'McBeal','isatown',333,'f','jan 79')");
stat.executeUpdate("INSERT INTO Customer VALUES (1003, 'Flinstone','hamad town',292,'m','may 72')");
stat.executeUpdate("INSERT INTO Customer VALUES (1004, 'Cramden','hamad town',987,'m','may 72')");
stat.executeUpdate("INSERT INTO Customer VALUES (1004, 'Cramden','hamad town',987,'m','may 72')");
stat.executeUpdate("INSERT INTO Customer VALUES (1004, 'Cramden','hamad town',987,'m','may 72')");*/
}//try
catch(Exception e)
System.out.println("Caught exception in main: " +e);
}//catch
//Create the JTable and build the GUI..
worker.updateTable();
}//main
//===========================================================================================================================
void makeGUI()
c.setLayout(new BorderLayout());
id = new JTextField(20);
name = new JTextField(20);
address=new JTextField(20);
phone=new JTextField(20);
sex=new JTextField(20);
dob=new JTextField(20);
add = new JButton("ADD");
update=new JButton("UPDATE");
panel = new JPanel();
buttonPanel = new JPanel(new GridLayout(3,4));
buttonPanel.add(new JLabel("ID",JLabel.CENTER));
buttonPanel.add(id);
buttonPanel.add(new JLabel("Name",JLabel.CENTER));
buttonPanel.add(name);
buttonPanel.add(new JLabel("Address",JLabel.CENTER));
buttonPanel.add(address);
buttonPanel.add(new JLabel("Phone",JLabel.CENTER));
buttonPanel.add(phone);
buttonPanel.add(new JLabel("Sex",JLabel.CENTER));
buttonPanel.add(sex);
buttonPanel.add(new JLabel("Date Of Birth",JLabel.CENTER));
buttonPanel.add(dob);
panel.add(add);
panel.add(update);
add.addActionListener(this);
search.addActionListener(this);
pack();
setVisible(true);
}//makeGUI
//===========================================================================================================================
public void actionPerformed(ActionEvent e)
if(e.getSource() == add)
if(id.getText().equals("") || name.getText().equals("") || address.getText().equals("") || phone.getText().equals("") || sex.getText().equals("")|| dob.getText().equals(""))
JOptionPane.showMessageDialog(null,"Please fill in the missing fields","Missing Fields!!!",JOptionPane.INFORMATION_MESSAGE);
try
String idInput = id.getText();
if(idInput.equals(""))
idInput = "0";
int userId = Integer.parseInt(idInput);
String userName = name.getText();
String userAddress = address.getText();
String userPhone = phone.getText();
String userSex = sex.getText();
String userDateBirth = dob.getText();
//logo=new ImageIcon("C:\My Documents\SENIOR\diagonal.jpg");
//Image img = Toolkit.getDefaultToolkit().getImage("diagonal.jpg");
String sql = "INSERT INTO CUSTOMER VALUES ('"+userId+"', '"+userName+"', '"+userAddress+"', '"+userPhone+"', '"+userSex+"', '"+userDateBirth+"')";
stat.executeUpdate(sql);
id.setText("");
name.setText("");
address.setText("");
phone.setText("");
sex.setText("");
dob.setText("");
updateTable();
repaint();
}//try
catch(Exception ee)
System.out.println("Caught exception in actionPerformed: "+ee);
}//catch
}//if
if(e.getSource()==update)
String idEntered = id.getText();
String enteredName=name.getText();
String enteredPhone=phone.getText();
String enteredSex=sex.getText();
String enteredDob=dob.getText();
try
catch(Exception eee)
System.out.println("Caught exception in actionPerformed: "+eee);
}//catch
}//else
}//actionlistener
//===========================================================================================================================
void updateTable()
try
int rowNumbers = 0;
//Get the number of rows in the table so we know how big to make the data array..
ResultSet results = stat.executeQuery("SELECT COUNT(*) FROM CUSTOMER");
while(results.next())
rowNumbers = results.getInt(1);
}//while
System.out.println("Rows: "+rowNumbers);
tableData = new String[rowNumbers][6];
int currentRow = 0;
ResultSet results1 = stat.executeQuery("SELECT * FROM CUSTOMER");
while(results1.next())
tableData[currentRow][0] = results1.getString(1);
tableData[currentRow][1] = results1.getString(2);
tableData[currentRow][2] = results1.getString(3);
tableData[currentRow][3] = results1.getString(4);
tableData[currentRow][4] = results1.getString(5);
tableData[currentRow][5] = results1.getString(6);
currentRow++;
}//while
//===============================================
//Create the table model:
final String[] colName = {"Id", "Name","Address","Phone","Sex","Date OF Birth"};
TableModel pageModel = new AbstractTableModel()
public int getColumnCount()
return tableData[0].length;
}//getColumnCount
public int getRowCount()
return tableData.length;
}//getRowCount
public Object getValueAt(int row, int col)
return tableData[row][col];
}//getValueAt
public String getColumnName(int column)
return colName[column];
}//getcolName
public Class getColumnClass(int col)
return getValueAt(0,col).getClass();
}//getColumnClass
public boolean isCellEditable(int row, int col)
return false;
}//isCellEditable
public void setValueAt(String aValue, int row, int column)
tableData[row][column] = aValue;
}//setValueAt
};//pageModel
//===========================================================================================================================
//Create the JTable from the table model:
dataTable = new JTable(pageModel);
//===========================================================================================================================
if(scrollpane != null)
scrollpane.setVisible(false);
scrollpane = null;
}//if
scrollpane = new JScrollPane(dataTable);
scrollpane.setVisible(true);
if(buttonPanel == null)
makeGUI();
c.add(buttonPanel, BorderLayout.NORTH);
c.add(panel, BorderLayout.CENTER);
c.add(scrollpane, BorderLayout.SOUTH);
id.grabFocus();
pack();
}//try
catch(Exception e)
System.out.println("Caught updateTable exception: "+e);
}//catch
}//updatetable
}//Jframe
i did the add part but know i'm stuck with the update..well this is my first time to work with databases using java ..
so please can someone help
thankxYes, I want find out how it works and what was the cause the program could not work.
-
Help! Using GUI button to update text file
Desperately needing help on the following:
As you will see, I have created two classes - one for reading and writing to a text file on my hard drive, and one for the GUI with two buttons - Display and Update. The Display button works perfectly in that it displays text from a file path. The Update button, however, does not work correctly. I seek for the Update button to update any edits to the same exact text file I view using the Display button.
Any help would be greatly appreciated. Thanks!
Class TextFile
import java.io.*;
public class TextFile
public String read(String fileIn) throws IOException
FileReader fr = new FileReader(fileIn);
BufferedReader br = new BufferedReader(fr);
String line;
StringBuffer text = new StringBuffer();
while((line = br.readLine()) != null)
text.append(line+'\n');
return text.toString();
} //end read()
public void write(String fileOut, String text, boolean append)
throws IOException
File file = new File(fileOut);
FileWriter fw = new FileWriter(file, append);
PrintWriter pw = new PrintWriter(fw);
pw.println(text);
fw.close();
} // end write()
} // end class TextFileClass TextFileGUI
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class TextFileGUI implements ActionListener
TextFile tf = new TextFile();
JTextField filenameField = new JTextField (30);
JTextArea fileTextArea = new JTextArea (10, 30);
JButton displayButton = new JButton ("Display");
JButton updateButton = new JButton ("Update");
JPanel panel = new JPanel();
JFrame frame = new JFrame("Text File GUI");
public TextFileGUI()
panel.add(new JLabel("Filename"));
panel.add(filenameField);
panel.add(fileTextArea);
fileTextArea.setLineWrap(true);
panel.add(displayButton);
displayButton.addActionListener(this);
panel.add(updateButton);
updateButton.addActionListener(this);
frame.setContentPane(panel);
frame.setSize(400,400);
frame.setVisible(true);
} //end TextFileGUI()
public void actionPerformed(ActionEvent e)
if(e.getSource() == displayButton)
String t;
try
t = tf.read(filenameField.getText());
fileTextArea.setText(t);
catch(Exception ex)
fileTextArea.setText("Exception: "+ex);
} //end try-catch
} //end if
else if(e.getSource() == updateButton)
try
tf.write(filenameField.getText());
catch(IOException ex)
fileTextArea.setText("Exception: "+ex);
} //end try-catch
} //end else if
} //end actionPerformed()
} //end TextFileGUIHere's your working example.
In my opinion u do not have to append \n when u reading the file
Look the source, if u have some problem, please, ask me.
Regards
public class TextFileGUI implements ActionListener
TextFile tf = new TextFile();
JTextField filenameField = new JTextField(30);
JScrollPane scrollPane = new JScrollPane();
JTextArea fileTextArea = new JTextArea();
JButton displayButton = new JButton("Display");
JButton updateButton = new JButton("Update");
JPanel panel = new JPanel();
JFrame frame = new JFrame("Text File GUI");
public static void main(String args[])
new TextFileGUI();
public TextFileGUI()
panel.setLayout(new BorderLayout());
JPanel vName = new JPanel();
vName.setLayout(new BorderLayout());
vName.add(new JLabel("Filename"), BorderLayout.WEST);
vName.add(filenameField, BorderLayout.CENTER);
panel.add(vName, BorderLayout.NORTH);
scrollPane.setViewportView(fileTextArea);
panel.add(scrollPane, BorderLayout.CENTER);
fileTextArea.setLineWrap(true);
JPanel vBtn = new JPanel();
vBtn.setLayout(new FlowLayout());
vBtn.add(displayButton);
displayButton.addActionListener(this);
vBtn.add(updateButton);
updateButton.addActionListener(this);
panel.add(vBtn, BorderLayout.SOUTH);
frame.setContentPane(panel);
frame.setSize(400, 400);
frame.setVisible(true);
} // end TextFileGUI()
public void actionPerformed(ActionEvent e)
if (e.getSource() == displayButton)
String t;
try
t = tf.read(filenameField.getText());
fileTextArea.setText(t);
catch (Exception ex)
ex.printStackTrace();
else if (e.getSource() == updateButton)
try
tf.write(filenameField.getText(), fileTextArea.getText(), false);
catch (IOException ex)
ex.printStackTrace();
} // end try-catch
} // end else if
} // end actionPerformed()
} // end TextFileGUI
class TextFile
public String read(String fileIn) throws IOException
String line;
StringBuffer text = new StringBuffer();
FileInputStream vFis = new FileInputStream(fileIn);
byte[] vByte = new byte[1024];
int vPos = -1;
while ((vPos = vFis.read(vByte)) > 0)
text.append(new String(vByte, 0, vPos));
vFis.close();
return text.toString();
} // end read()
public void write(String fileOut, String text, boolean append) throws IOException
File file = new File(fileOut);
FileWriter fw = new FileWriter(file, append);
PrintWriter pw = new PrintWriter(fw);
pw.println(text);
fw.close();
} // end write()
} // end class TextFile -
Need help in Simple Java JDialog...
have 3 classes..
One class extend JFrame
One class extend JPanel
One class extend JDialog
My JFrame is like my Main Frame...
I have my JPanel that is always changing in my JFrame..
How do i pass the JFrame into my JDialog constructor???
(btw, is upon one of my JPanel click button, my JDialog appears)
Thanks.have 3 classes..
One class extend JFrame
One class extend JPanel
One class extend JDialog
My JFrame is like my Main Frame...
I have my JPanel that is always changing in my
JFrame..
How do i pass the JFrame into my JDialog
constructor???
(btw, is upon one of my JPanel click button, my
JDialog appears)
Thanks.You can pass the reference of JFrame in JDialog constructor as below:
1) JDialog dialog = new JDialog(ClassName.this, "Title', true);
where ClassName is the name of class that extends the JFrame. Thus you can capture reference of the parent.
2) You can also get reference of JFrame by invoking method on your panel as:
Container parent = jPanel.getParent();
JDialog dialog = new JDialog(parent , "Title', true);
where jPanel is instance of your JPanel.
Post whether u need anything else.
Maybe you are looking for
-
Is there a link that I can enter a serial number to see if an apple product is swwtolen?
I am looking to find out if and where there is a website I can enter a serial number to find out if a 2005 mac mini is stolen?
-
How to deinstall Oracle Developer 2000 6i and again install properly
hi My HDD is partitioned as C,D,E and F. Oracle 9i is successfully installed in my system in C:\ drive (C:\oracle)and it's running fine. when i was going to install Oracle Developer 2000 6i in F:\ drive it dint show neither any error message nor mess
-
Hi I want to take data from a mySQL database and show it in an applet as a graph. The problem I'm having is creating the graph. Does anyone know a fairly simple way to do this? thanks
-
How to use SELECTION-SET with FREE-SELECTIONS?
Hi, how to use SELECTION-SET with FREE-SELECTIONS? Regards, Vinay.
-
Error 131-46 GL account not found
HI Expets I had to post a AR invoice using a delivery note. After creating the AR invoice when i tried to add it, it gave me a warning that the customers credit limit is already passed and asked do you want to continue. after selecting yes it gave me