Repainting a panel

I have a program that get's different info from a mysql database. Part of the program is to add new items to the database. I have a combo box that has a list of all the customer names. This is the first column in the database. My question is when someone edits or adds a new customer I want to refresh or repaint the screen so that the changes they made in the database show up in the program. What is the best way to do this. I've tried repaint but that is not working. Not sure what I need to be repainting.

Repainting will only be the last step you need to take.
You will need to re-populate the model of the combo-box (I'm assuming you are talking about a Swing application here).

Similar Messages

  • How to repaint a panel

    Hi All!
    I am trying to display a few textFields in an AWT applet. The number of textFields I need to set is variable. I want to repaint a portion of an applet (the panel in which these textFields are placed) when a button is clicked.
    In the code below, I added a textField array in panel 1(p1), initialized with record size (no_of_rec), which I know at the beginning (no_of_rec = 2 at INDEX = 0).
    When I click "Next Item" button, I want to show 4 textFields (no_of_rec = 4 at INDEX = 1), with the values C, D, E, F.
    One more click (INDEX = 2) should show one textField only, with the value X.
    The codes for the textFields are in a method(addDataPanel), so that I can call it when I click "Next Item" button. A system.out check shows that 4 textFields are created when INDEX = 1, and so on, but with calling repaint() inside the button's actionPerformed method, I am unable to update the panel (p1) dynamically.
    When I minimize the window with [-] button, and get back to the original size, I can see the no of textFields have increased to 6; 2 from the beginning and 4 from the first click.
    Could someone please help?
    Thank you.
    Tienshan
    Here is my code:
    import java.awt.*;                           
    import java.applet.*;                       
    import java.awt.event.*;
    public class test1020 extends Applet{
         int NO_OF_REC = 0;
         int INDEX = 0;
         TextField[] txtDataRowDisplay;
         String[] data;
         Panel p1;
         GridBagConstraints c1;
         Color pnlBgColor = new Color(144, 196, 222);
         public void init() {     
              data = getData(INDEX);
              NO_OF_REC = data.length;
              //main Panel
              Panel pMain = new Panel();
              pMain.setLayout(new GridBagLayout());
              GridBagConstraints c  = new GridBagConstraints();
              pMain.setBackground(pnlBgColor);
              //p0
              Panel p0 = new Panel();
              p0.setLayout(new GridBagLayout());
              GridBagConstraints c0  = new GridBagConstraints();
              c0.fill = GridBagConstraints.HORIZONTAL;
              p0.setBackground(pnlBgColor);
              //p1
              p1 = new Panel();
              p1.setLayout(new GridBagLayout());
              c1  = new GridBagConstraints();
              Button btnNext = new Button("Next Item");
              c0.insets = new Insets(0, 0, 10, 0);
              c0.gridx = 3;
              c0.gridy = 0;
              p0.add(btnNext, c0);
              btnNext.addActionListener(
                   new ActionListener() {
                        public void actionPerformed(ActionEvent e){
                             INDEX++;     
                             data = getData(INDEX);
                             NO_OF_REC = data.length;
                             addDataPanel(p1, c1);
                             display(data);
                             p1.repaint();
              //call a method to add data row(s)
              addDataPanel(p1, c1);
              //add p0 and p1 to pMain;
              c.gridx = 0;
              c.gridy = 0;
              pMain.add(p0, c);
              c.gridx = 0;
              c.gridy = 1;
              pMain.add(p1, c);
              add(pMain);
              this.setBackground(pnlBgColor);
              display(data);
         }//init
         private String[] getData(int index){
              if(index == 0){
                   String[] names = { "A", "B" };
                   return names;
              else if (index==1) {
                   String[] names = { "C", "D", "E", "F" };
                   return names;
              else {
                   String[] names = { "X" };
                   return names;
        private void addDataPanel(Panel p1, GridBagConstraints c1){
              txtDataRowDisplay = new TextField[NO_OF_REC];
              for(int i = 0; i < NO_OF_REC; i++){
                   txtDataRowDisplay[i] = new TextField(4);
              int cnt = 0;
              for(int m = 0; m < txtDataRowDisplay.length; m++ ){
                   c1.gridx = 0;
                   c1.gridy = m + cnt;
                   p1.add(txtDataRowDisplay[m], c1);
                   cnt++;
         private void display(String[] data){
              for(int i = 0; i < data.length; i++){
                   txtDataRowDisplay.setText(data[i]);

    BickelT , yes, it does work! I am almost there, only a small hurdle. When I initialize my textFields with a bigger size, all the smaller sizes are painted correctly. But when the initial size (when index is 0, that is at the time of init) is small, all the subsequent sizes are fixed to that init size.
    For example, when I change my code to the following, it works fine.
    private String[] getData(int index){
              if(index == 0){
                   String[] names = { "C", "D", "E", "F" };
                   return names;
              else if (index==1) {
                   String[] names = { "A", "B" };
                   return names;
              else {
                   String[] names = { "X"};
                   return names;
         } With the code as it is (as posted originally), in the first click, a textField with space(=height) for two textFields is painted with the value C and the lower half is empty. It is refusing to draw the area bigger than the init size of 2. When I resize the applet, I can see that four textFields with the values C, D, E, F.have been painted.
    I added the codes you suggested inside the addActionListner class. Isn't that the correct place to add the codes?
    BTW, with or without p1.repaint, the result is the same.
    What could have gone wrong?
    Thank you.

  • Repaint() in panel

    I have overridded the update method in a class I extended from panel. I first call my paint method then the standard paint method, like so:
    public void update(Graphics g)
    Dimension d = getSize();
    // clear the exposed area
    g.setColor(Color.black);
    g.fillRect(0, 0, d.width, d.height);
    g.setColor(Color.white);
    //Custom Repaint
    ModPaint(g);
    // do normal redraw
    paint(g);
    This works if I call the repaint() method by hand, but if the screen is resized or minimized and restored I get a white screen, the ModPaint() method is never called. Is there a different method that is called that I need to put my repaint in when the screen is resized or changed?
    Thanx

    And if your repainting is very slow, then you could consider using a buffered image to draw on, and in the paint method only paint this image (the modification whenever needed is done to the buffered image).

  • When to repaint panel?

    I'm having a problem figuring out when exactly my panel is ready to be repainted. Inside this JPanel I'm loading Images and then drawing them with paintComponent. My problem is that when the panel is first painted, these images aren't loaded yet so paintComponent can't draw them. However, after a second or so these images are loaded and if I force a repaint by resizing the window everything shows up fine.
    What's the best way to repaint the panel when the Images are loaded? I tried a thread approach but I was running into problems where for some reason the images would never load (as if the thread was taking over the whole program) and I would like to avoid threads if possible. Any suggestions would be greatly appreciated.

    Synchronous loading means that your application stops everything until the image is fully-loaded, then continues on its way. Asynchronous loading means the app moves ahead without loading the image; not a desirable thing. The old boiler plate method for synchronous loading is with a MediaTracker. The newer way is with ImageIO but this requires j2se 1.4 or later. If you will load or initiate the loading of your images in the constructor of your app/component they will be ready when the app/component is first painted.
    class AnImageComponent extends JPanel
        BufferedImage/Image image;
        public AnImageComponent()
            loadImage();
        protected void paintComponent(Graphics g)
            g.drawImage(image, x, y, this);
        private void loadImage()
            // synchronously load image...
    }The override of the 'update' method is not recommended and usually not necessary in Swing. Calling 'repaint' and/or 'validate/revalidate' for updating gui components is usually done from within event code, eg, from within the actionPerformed method of a SwingTimer, a while loop inside an animation thread, or a ui component event listener.

  • Problem with Paining in a Panel in a JFrame.

    So I can paint directly on a JFrame, and I can paint on a class that extends Panel, and put the Panel on a JFrame. But if I try to Repaint the Panel it won't show on the JFrame. Do I have to do anything to the JFrame to show the changes to the objects inside as well?

    I'm not sure if you've done this, but don't change the paint method when using Swing components, use paintComponent instead. By default, the JFrame will paint its children. Just remember whenever overriding any of the paintComponent methods to call super.paintComponent(g) first.

  • Adding a panel to a frame

    Hi! All,
    I'm new to java and i have a little problem here. I have created a frame and i want to put two panels inside it. well, i managed to put the first one, but i'm having problems with the second one. I want this second one to be added when I click on a button.
    The button that I will click is the new JButton i have defined. it is called draw. I really do not know what the problem is. I will apprecite any help. Below is my code.
    // My Code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.util.*;
    public class Main extends JFrame {
    //all components I'll need
    public JButton draw;
    public JButton addFormula;
    public JButton modelCheck;
    /** Creates a new instance of Main */
    public Main () {
    super("Graphical Model Checker for Knowledge");
    //content pane is the main panel where i'll put everything
    JPanel contentPane = new JPanel();
    draw = new JButton("Draw");
    draw.addActionListener(
    new ActionListener() {         
    public void actionPerformed(ActionEvent event) {
    if(event.getActionComman().equals"Draw")) {               
    JPanel drawing = new JPanel();
    drawing.setBackground(Color.BLUE);
    drawing.setSize(100, 100);
    drawing.setLayout(new FlowLayout
    FlowLayout.CENTER));
    add("North", drawing);
    drawing.setVisible(true);
    contentPane.add(draw);
    addFormula = new JButton("Add Formula");
    contentPane.add(addFormula);
    modelCheck = new JButton("Model Check");
    contentPane.add(modelCheck);
    Canvas canvas = new Canvas();
    canvas.setSize(40, 40);
    canvas.setBackground(Color.white);
    contentPane.add(canvas);
    repaint();
    //add panel to the frame
    add("South", contentPane);
    //colours for window
    contentPane.setBackground(Color.yellow);
    //set layout manager
    contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));
    addWindowListener(new CloseWindow());
    pack();
    setVisible(true);
    String [] fileItems = {"Open", "Save", "Rename"};
    String [] editItems = {"Copy", "Cut", "Paste"};
    //instantiate a menu bar object
    JMenuBar bar = new JMenuBar();
    JMenu file = new JMenu("File");
    for (int index=0; index != fileItems.length; index++)
    file.add(fileItems[index]);
    bar.add(file);
    setJMenuBar(bar);
    JMenu edit = new JMenu("Edit Graph");
    for (int index=0; index != editItems.length; index++)
    edit.add(editItems[index]);
    bar.add(edit);
    setJMenuBar(bar);
    public static void main(String args []) {
    JFrame window = new Main();
    }

    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.
    add("North", drawing); The "North" means nothing when adding a component to a panel using a FlowLayout. You should just be using:
    add( drawing );After you add the component to the container you need to use:
    frame.validate();

  • Does repaint() not call paint()?

    I try to create a application where pictures are switching randomly one after another. User can specific how long this randomly displaying image application run. Then when the user click "start", the image will randomly change until it is timeout. As far as I know, I have this part finish.
    However, I want to add another part: when user click start a small clock display on the panel the amount of second counting down. However, when I set the timer to repaint() the application, it does not get in the paint() method. Below are my code, please help. Since my code are a bit long, I will post my entire code on a separate thread, hope that the admin and mod dont mind.
    This is where I implement paint(), and I click on the button, I repaint the panel
    public void paint(Graphics g)
            System.out.println("Inside Graphics");
            //Create an instance of Graphics2D
            Graphics2D g2D = (Graphics2D)g;
            g2D.setPaint(Color.RED);
            g2D.setStroke(stroke);
            DigitalNumber number = new DigitalNumber(numberX,numberY,numberSize,numberGap,Color.red, Color.white);
            //Get the time that the user input to the field
            String time = tf.getText();
            float locX = numberX;
            float locY = numberY;
            //Start drawing the number onto the panel
            for(int i=0; i<time.length(); i++){
                 number.drawNumber(Integer.parseInt(Character.toString(time.charAt(i))), g2D);
                 locX += numberSize + numberGap;
                 number.setLocation(locX, locY);
    private void createBtnPanel() {
          JButton startBtn = new JButton("Start");
          JButton stopBtn = new JButton("Stop");
          startBtn.addActionListener(new StartBtnListener() );
          stopBtn.addActionListener(new StopBtnListener());
          btnPanel.add(startBtn, BUTTON_PANEL);
          btnPanel.add(stopBtn, BUTTON_PANEL);
    private class StartBtnListener implements ActionListener {
          public void actionPerformed(ActionEvent e) {
             //get the time from the user input
             String input = tf.getText();
             numberOfMilliSeconds = Integer.parseInt(input)*1000;
             //get the current time
             startTime = System.currentTimeMillis();
             java.util.Timer clockTimer = new java.util.Timer();
             java.util.TimerTask task = new java.util.TimerTask()
                 public void run()
                      mainPanel.repaint();
             clockTimer.schedule(task, 0L, 1000L);
             rotatePictureTimer.start();
       }

    I am sorry. However, even though I try to make my code self contained, it still too long to post here. It is the DigitalNumber.java that contain all the strokes for draw the number is all too long. But I can tell you that DigitalNumber.java is worked because I wrote a digital clock before, and it worked. But below is the link to my DigitalNumber.java if u guy want to look at it
    http://www.vanloi-ii.com/code/code.rar
    Here is my code for DisplayImage.java in self-contain format. Thank you
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.*;
    public class DisplayImage{
       private static final Dimension MAIN_SIZE = new Dimension(250,250);
       private static final String BUTTON_PANEL = "Button Panel";
       private JPanel mainPanel = new JPanel();
       private JPanel btnPanel = new JPanel();
       private JPanel tfPanel = new JPanel();
       private BorderLayout borderlayout = new BorderLayout();
       private JTextField tf;
       BasicStroke stroke = new BasicStroke(5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL);
       private float numberX = 100f;
       private float numberY = 100f;
       private float numberSize = 10f;
       private float numberGap = 2f;
       public DisplayImage() {
          mainPanel.setLayout(borderlayout);
          mainPanel.setPreferredSize(MAIN_SIZE);
          createTFPanel();
          createBtnPanel();
          mainPanel.add(tfPanel, BorderLayout.NORTH);
          mainPanel.add(btnPanel, BorderLayout.SOUTH);
       public void paint(Graphics g)
            System.out.println("Inside Graphics");
            //Create an instance of Graphics2D
            Graphics2D g2D = (Graphics2D)g;
            g2D.setPaint(Color.RED);
            g2D.setStroke(stroke);
            DigitalNumber number = new DigitalNumber(numberX,numberY,numberSize,numberGap,Color.red, Color.white);
            //Get the time that the user input to the field
            String time = tf.getText();
            float locX = numberX;
            float locY = numberY;
            //Start drawing the number onto the panel
            for(int i=0; i<time.length(); i++){
                 number.drawNumber(Integer.parseInt(Character.toString(time.charAt(i))), g2D);
                 locX += numberSize + numberGap;
                 number.setLocation(locX, locY);
       private void createBtnPanel() {
          JButton startBtn = new JButton("Start");     
          startBtn.addActionListener(new StartBtnListener() );    
          btnPanel.add(startBtn, BUTTON_PANEL);
       private void createTFPanel() {
          JLabel l = new JLabel("Enter Number of Seconds: ");
          tf = new JTextField(3);
          tfPanel.add(l);
          tfPanel.add(tf);
       private class StartBtnListener implements ActionListener {
          public void actionPerformed(ActionEvent e) {
             //get the time from the user input
             java.util.Timer clockTimer = new java.util.Timer();
             java.util.TimerTask task = new java.util.TimerTask()
                 public void run()
                      System.out.println("TimerTask");
                      mainPanel.repaint();
             clockTimer.schedule(task, 0L, 1000L);     
       private static void createAndShowUI() {
           DisplayImage displayImage = new DisplayImage();
          JFrame frame = new JFrame("Display Image");
          frame.getContentPane().add(displayImage.mainPanel);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setBackground(Color.white);
          frame.pack();
          frame.setLocationRelativeTo(null);  //center the windows
          frame.setVisible(true);
       public static void main (String args[]) {
          java.awt.EventQueue.invokeLater(new Runnable(){
             public void run() {
                createAndShowUI();
    }Edited by: KingdomHeart on Feb 22, 2009 6:12 PM

  • Panel field display when process is running

    I am developing a program that needs to update the panel to give status information about a process that is running. SO far the panel only appears to repaint when the process completes - is there a way to force a repaint without a break in a process?
    I have tried setting teh field any issuing a repaint instruction, but this only seems to take effect when the program reaches its end point.
    Any suggestions?

    Hi,
    Repainting the panel while the process is going on is tricky. In the single threaded model, which I guess you are using, the panel will get repainted only when the process is complete.
    You can use a multithreaded model.
    You can assign two threads, one thread for repainting and another for doing the process. But we cannot predict exactly when the thread will be called.
    A better idea would be to have a timer variable. A variable which goes on counting and say, every 10000 counts , calls the repaint method.

  • Better looking repost: Strange panel behavior

    Well, I am making a game of Deal or No Deal for my Computer Science class, and I have run into what appears to be a random bug in the code or something. I have 5 Panels, with 6 cases on the first four and 2 on the bottom panel. The cases are buttons which send to an action performed, if it is the first click, it runs it through a little series, as such:
    int i=Integer.parseInt(evt.getActionCommand());
    //This part just sets the number aside for later, to be called up at the end of the game
    game.makeTheChosenOne(evt.getActionCommand());
    //This is the slacker way I have of removing the case no matter what panel is clicked
    cp.remove(theCase);
    Panel1.remove(theCase);
    Panel2.remove(theCase);
    Panel3.remove(theCase);
    Panel4.remove(theCase);
    Panel5.remove(theCase);
    PanelAll.remove(theCase);
    /*0,6,12,18,24*/
    //The println just lets me see what array index is used
    System.out.println(i);
    // This should replace a black image with the case that is first clicked
    caseLabel.add(theCase);
    //Panels 1-5
    Panel1.repaint();
    Panel2.repaint();
    Panel3.repaint();
    Panel4.repaint();
    Panel5.repaint();
    //Main Panel they sit on
    PanelAll.repaint();
    //This is where the Cases SHOULD show up
    caseLabel.repaint();
    // cp= Container for ContentPane
    cp.repaint();
    }Now, in the code, you can see the /*0,6,12,18,24*/ comment, I put this in here, because for some reason, those are the only index's that actually output the case image to caseLabel. For the first click, all of them should. The remove case part works flawlessly, but for some reason, only the first case on every Panel works when outputting it to the Panel.
    incase you can't imaging it...(the index is in parentheses)
    1(0) 2(1) 3(2) 4(3) 5(4) 6(5)
    7(6) 8(7) 9(8) 10(9) 11(10) 12(11)
    13(12) 14(13) 15(14) 16(15) 17(16) 18(17)
    19(18) 20(19) 21(20) 22(21) 23(22) 24(23)
    25(24) 26(25)
    Only the first one in every set works correctly(1(0),7(6),13(12),19(18), and 25(24).
    This is a re-post, I could not find an edit button for my first post, and others said to use code tags, also, I was hurried to finish the post before, so I could not elaborate.
    Basically, the cases are on the 5 Panels, which are all on one big panel. All the extra repaints really don't matter, they are just there to make sure NOTHING slips through, since this bug is annoying me.
    Basically, on the first click of the game, you are choosing 'your case', The case that you hold until the end if you don't take the banker's offer given at certain times. When you click on the case you want(it is a button) it goes to the actionlistener, which checks to make sure it is indeed the first click, then removes that case from the row.
    That part works perfectly, no matter what case is clicked it is removed.
    Now for the problem, like stated above, only the first button on every panel of cases is actually being relocated to a bottom panel, which holds a place for the case to go. Basically, there is a blank image/space there, that gets replaced by the case you pick. I know this 'works' because the first cases in the case panels work correctly, however, the other 21 cases do not go there for some reason.
    Good: http://i44.photobucket.com/albums/f38/ichp00ndu/casegood.jpg
    Bad:http://i44.photobucket.com/albums/f38/ichp00ndu/casemessedup.jpg

    Since I don't see an Edit button...
    Panel1.remove(theCase);
    Panel2.remove(theCase);
    Panel3.remove(theCase);
    Panel4.remove(theCase);
    Panel5.remove(theCase);
    PanelAll.remove(theCase);
    /*0,6,12,18,24*/
    //The println just lets me see what array index is used
    System.out.println(i);
    // This should replace a black image with the case that is first clicked
    caseLabel.add(theCase);
    //Panels 1-5
    Panel1.repaint();
    Panel2.repaint();
    Panel3.repaint();
    Panel4.repaint();
    Panel5.repaint();
    //Main Panel they sit on
    PanelAll.repaint();
    //This is where the Cases SHOULD show up
    caseLabel.repaint();I changed this to:
                       PanelAll.remove(theCase);
         /*0,6,12,18,24*/
         System.out.println(i);
         caseLabel.add(theCase[i]);
         PanelAll.repaint();
    Still has the same problem though
    Message was edited by: OP
    bizkut

  • Repaint() for JPanels

    HI ALL,
    I am doing a line plot of image data, and displaying it on a JPanel.
    In my App, I added some buttons for I can transition between the plots.
    I can grab all the data at once and display all in separate tabs, but
    when I changed it to this buttons format, the plot never updates.
    Here is my button function to update the panel.
         myPrevButton.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent ae) {
                        try{
                             p = (Plotable)myPlotables.elementAt(currentPlot-2);
                        myMeanPlotPanel = new XYPlotJPanel(p);
                   p = (Plotable)list.nextElement();
                             currentPlot = myPlotables.indexOf(p);
              mySDPlotPanel = new XYPlotJPanel(p);
                             myMainPanel.repaint();
              } catch (NotEnoughDataException nede){
                   MsgPopup msg = new MsgPopup(LocalizedError.constructFormattedErrorString(nede));
                   msg.show();
    When I read the images, I use a vector to order the images, and "list" is an enumertion variable in this function.
    The mainPanel holds both subpanels. Now the app will show only the first plot, but will not update any other plots. I have tried repaint() all panels before, it did not work.
    Does anyone know how to get this to update or replot,refresh, ...or etc....?
    I have not ideas now.
    Thanks!

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class SelectingGraphs {
      static int plotIndex = 0;
      public static void main(String[] args) {
        float[] data1 = {
          1.2f, 2.0f, 3.7f, 4f, 2.9f, 4.9f, 3.1f, 4.02f
        float[] data2 = {
          29f, 18.2f, 75f, 34f, 92f, 15f, 50.9f, 42.3f
        float[] data3 = {
          90f, 44f, 53.7f, 67.2f, 49.2f, 79f, 80.3f, 55.2f
        final float[][] allData = {
          data1, data2, data3
        Plot
          plot1 = new Plot(),
          plot2 = new Plot(),
          plot3 = new Plot();
        final Plot[] plots = {
          plot1, plot2, plot3
        for(int i = 0; i < plots.length; i++)
          for(int j = 0; j < allData.length; j++)
    plots[i].plot(allData[i][j]);
    final JPanel panel = new JPanel();
    panel.add(plot1);
    // south panel
    final JButton
    lastButton = new JButton("last"),
    nextButton = new JButton("next");
    ActionListener l = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JButton button = (JButton)e.getSource();
    panel.remove(plots[plotIndex % 3]);
    if(button == lastButton) {
    --plotIndex;
    if(plotIndex < 0)
    plotIndex = 2;
    if(button == nextButton)
    ++plotIndex;
    panel.add(plots[plotIndex % 3]);
    panel.revalidate();
    panel.repaint();
    lastButton.addActionListener(l);
    nextButton.addActionListener(l);
    JPanel southPanel = new JPanel();
    southPanel.add(lastButton);
    southPanel.add(nextButton);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(panel);
    f.getContentPane().add(southPanel, "South");
    f.setSize(400,300);
    f.setLocation(400,300);
    f.setVisible(true);
    class Plot extends JPanel {
    float PAD = 25;
    List dataList;
    public Plot() {
    dataList = new ArrayList();
    setBackground(Color.white);
    setPreferredSize(new Dimension(200,200));
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    float width = getWidth();
    float height = getHeight();
    float xStep = (width - 2*PAD)/(dataList.size() - 1);
    float x = PAD;
    float y;
    // scale data
    float max = ((Float)Collections.max(dataList)).floatValue();
    float min = ((Float)Collections.min(dataList)).floatValue();
    float vertSpace = height - 2*PAD;
    float yOffset = height - PAD;
    float yDataOffset = (min >= 0 ? min : max > 0 ? 0 : max);
    float scale = vertSpace/(max - min);
    float yOrigin = yOffset + (min > 0 ? 0 : max > 0 ? scale*min : - vertSpace);
    // draw ordinate
    g2.draw(new Line2D.Float(PAD, PAD, PAD, yOffset));
    // draw abcissa
    g2.draw(new Line2D.Float(PAD, yOrigin, width - PAD, yOrigin));
    // label ordinate limits
    g2.drawString(String.valueOf(max), 10, PAD - 10);
    g2.drawString(String.valueOf(min), 10, yOffset + PAD/2);
    g2.setStroke(new BasicStroke(4f));
    g2.setPaint(Color.red);
    for(int j = 0; j < dataList.size(); j++) {
    y = yOrigin - scale * (((Float)dataList.get(j)).floatValue() - yDataOffset);
    g2.draw(new Line2D.Float(x, y, x, y));
    x += xStep;
    protected void plot(float input) {
    dataList.add(new Float(input));
    repaint();

  • Repaint

    I'm trying to make a small city simulator game. I have a two-dimensional table (40 * 40), which is drawn on a JPanel using small gifs. Every time when player builds something and the table changes, the program repaints the panel. The problem is that this is very slow. How could I do it faster?

    There are two version of the repaint method: one that repaints the whole component and one that repaints only a certain area of the component. You could try the latter one. See also this article:
    http://java.sun.com/products/jfc/tsc/articles/painting/index.html

  • Applets and Panels

    Hi Guys,
    I have an applet that builds a panel and a button on the panel. When I move the applet of course it disappears how can I get the applet to repaint the panel in my following code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    * box.java
    * Created on November 22, 2002, 11:06 AM
    public class Box1 extends JApplet {
        private int x = 0;
        private int y = 0;
        private int w = 0;
        private int h = 0;
        public  Box1 (int x, int y, int w, int h) {
            this.x = x;
            this.y = y;
            this.w = w;
            this.h = h;
        public Box1(){
        public void init()
          JPanel p = new JPanel();
          JButton b = new JButton();
          setSize(400,400);
          p.setSize(200,200);
          p. setBorder (new BevelBorder (BevelBorder.RAISED));
          b.setSize (75,75);
          b.setVisible (true);
          p.add(b);
          p.setVisible (true);
          getContentPane().add(p);
          setVisible(true);
       public void paint(Graphics g)
    }Also I have tried to put the code that creates the panel and button in the paint method but nothing happens, why?
    My goal is to create a box class that can create a panel that will reside in another applet. But right now I am testing the box class in an Applet. Later I will seperate the two. This is unreal why is creating graphics in applets such a pain in the kester.
    Thanks,
    JJ
    Thanks in Advance,
    JJ

    Either take the paint method out entirely or put the line
    super.paint(g)
    in it. By having this empty method in your code, you the method which actually handles the painting isn't being called.

  • JTabbedPane repainting issue

    when i repaint a panel that has a tabbedPane the components from other tabs bleed through the selected one, which is indice 0
    I have a JFrame borderlayout like this
    Container c = frame.getContentPane();
    c.add("West", jList);
    c.add("Center", panel);
    the panel is borderlayout as well like this
    panel.add("North", panel2);
    panel.add("Center", tabbedPane);
    the jList has about 10 items all of which need to remove and repaint panel depending on the selected item in list.
    so I do this:
    in a valueChanged method cause i implement ListSelectionListener
    int index = jList.getSelectedIndex();
    if(index == -1) return;
    c.remove(panel);
    if(index == 0) c.add("Center", new SomeClass());
    else if(index == 1) c.add("Center", new SomeClass2());
    else if(.....) ect....
    // then i do this
    c.invalidate();
    c.validate();
    c.update(c.getGraphics());
    seems to work and i get matching content to list selection, and all components are visible. but compoenets from tabs underneath the currently selected one bleed through. when i click on one of the other tabs, and click back to the first one, the problem is gone. if i choose something else from the jList, the problem starts all over again.

    found the issue - nevermind
    seems like I had old references to objects originally displayed on the panels that sat on TabbedPane
    so when i went tried to bring back an item in jList, i had a mess of old components lingering around.

  • How to change  panel's content ??

    hi
    i just tried to remove the older contents and repaint the panel then add the new contents ,but this try didnt work.
    what do you think?
    how can i change the contents?

    After you add or remove components from a panel you need to revalidate() the panel.
    Or, maybe a Card Layout is a better approach:
    http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html

  • How Java2D repaint( ) works?

    Never mind my problem with not drawing lines. Found the error myself. But it is still greatly appreciated if you could explain how repaint( ) works.
    << Edit ends >>
    Old post:
    I am very new to Java2D. I am programing an application that need GUI and 2D and got curious about how a panel with '2D' image updates the content.
    The program has GUI interface with all menu and buttons, displaying an empty 'content' panel in the middle at the start. Information will be read in from a file and the program should display series of boxes like this:
    |    |        |     |             | |        |         |
    and another one
    |           | |      |           |  |              |   |
    --------------------------------------------------------Then, a button named 'align' will match the box stretches between two neighboring series, and the program suppose to display like this:
    |    |        |     |             | |        |         |
                        |                        |
    |______________________|_______________________________
    |             | |      |           |  |           |   |
    --------------------------------------------------------pseudo code for related components is like this:
    public class alignbox {
      private Boxes[ ]boxes; // store information of box series
      private Alignment aln; // store informations of alignment
      private jFrame frame;
      private jButton[ ] quite_a_few_buttons;
      private DrawPanel pane = new DrawPanel( );
      ... // after button is clicked
      frame.getContentPane( ).repaint( );
      // "content panel"
      private class DrawPanel {
       public DrawPanel( ) {
         init( );
       void init( ) {
          Shape[ ] boxShapes = new Shape[ numOfSeries ];
          for (each bs of boxShapes)
             bs = getPath (boxes);
         Shape[ ] alignedLines = new Shape [numOfSeries -1];
          for (each line of alignedLines)
              line = getPath (aln);
      void paintComponent(Graphics g){
            init( );
            // draw boxes after "open" file
            // daw boxes and alignment lines after "align" button pressed
    }from what I read, paintComponent(Graphics g) is the main play displaying images I want. I can get boxes display fine, but I couldn't get alignment line displayed at all.
    Does repaint( ) call paintComponent( ) at all? I include 'init( )' in the paintComponent( ). will it allow the updates of boxes[ ] and aln reflected in the DrawPanel?
    if not, how do I 'tell' DrawPanel that boxes infor or alignment info has been updated and redisplay the content? Should there be a better way to do so unlike my clumsy method?
    Thanks!

    Swing related questions should be posted in the Swing forum.
    The repaint() invokes the paint() method which in turn ivokes the paintComponent() method (among others). Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/14painting/index.html]Painting for more information.

Maybe you are looking for

  • TS3988 My iCloud account is not my apple id account. How do I switch to the correct account?

    My Icloud is not backing up any of my devices. The icloud states a mac Apple ID and I have a gmail ID. How do I switch to the correct ID?

  • Form won't distribute. Here's the error and everything I've tried so far. Hope you can help

    I've seen at least 2 similar posts on the web, but they ended with no answer. After creating my form with LiveCycle Designer, saving as pdf, and hitting "DISTRIBUTE", I get this error: "The filename you specified is not valid because it does not incl

  • Render html form & send forms's input values as params via HTTP POST

    Hello, I'm using appache commons http client to send HTTP post queries to a given url and receive HTTP response then process it. one of the requirements of my Application is the following: one of these HTTP Post requests is supposed to return an HTML

  • IWeb 2.0 bugs

    Bugs: iWeb 2.0 crashes upon publish - I reported via crash log. iWeb 2.0 completely screwed up all pages containing photos. Here are some examples: http://www.mrconsultingservices.com/files/apple/iweb20bug1.png http://www.mrconsultingservices.com/fil

  • CPU intensive query

    Hi, on 11g R2 64 bits on Win 2008 R2, when query runs CPU is used at 100%. AWR says : Event                                 Waits     Time(s)   (ms)   time Wait Class DB CPU                                            2,805          80.1 db file seque