JPanel Alignment

It's possible to align (Y axis) two diferent JPanels?
For example, if I have two diferent JPanels inside a JFrame and I want that this two JPanels start in the same Y position, but they have diferent sizes(Height) . It's that possible without doing absolute positioning??
Thanks.

Use BoxLayout with BoxLayout.PAGE_AXIS

Similar Messages

  • Setting a JPanel alignment

    hi all,
    I'm using a BorderLayout for my simply application.
    I have created a JPanel that contains two buttons, as follows:
    JPanel pannello_pulsanti=new JPanel();
    pannello_pulsanti.setLayout(new BoxLayout(pannello_pulsanti, BoxLayout.LINE_AXIS));
    salva.setPreferredSize(new Dimension(100, 20));
    salva.setMaximumSize(new Dimension(100, 20));
    reset.setPreferredSize(new Dimension(100, 20));
    reset.setMaximumSize(new Dimension(100, 20));
    pannello_pulsanti.add(salva);
    pannello_pulsanti.add(Box.createRigidArea(new Dimension(0, 5)));
    pannello_pulsanti.add(reset);I had in mind to put the JPanel inside the "PAGE_END" location, and I did it.
    the problem is that the panel has a left alignment, while I want a center alignment for it (I tried to change its alignment with setAlignmentX method, but it doesn't work).
    can anyone help me in solving this problem?
    thanks,
    varying

    import java.awt.*;
    import javax.swing.*;
    public class CenteringComponents
        public static void main(String[] args)
            JButton button1 = new JButton("Button 1");
            JButton button2 = new JButton("Button 2");
            Box centerBox = Box.createHorizontalBox();
            centerBox.add(Box.createHorizontalGlue());
            centerBox.add(button1);
            centerBox.add(Box.createHorizontalGlue());
            centerBox.add(button2);
            centerBox.add(Box.createHorizontalGlue());
            JButton button3 = new JButton("Button 3");
            JButton button4 = new JButton("Button 4");
            Box southBox = Box.createHorizontalBox();
            southBox.add(Box.createHorizontalGlue());
            southBox.add(button3);
            southBox.add(Box.createHorizontalGlue());
            southBox.add(button4);
            southBox.add(Box.createHorizontalGlue());
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(centerBox);
            f.getContentPane().add(southBox, BorderLayout.PAGE_END);
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Repaint() in JPanel doesn't align correctly

    Hey all,
    I'm running into this problem with a program I'm writing for work. It's basically a dispatch board which connects to our SQL server via ODBC. When the user presses a "Next" or "Prev" button, the dates will change and show the dispatching for the next or previous week respectively. However, the refreshed components go where they are supposed to, but the old screen is underneath, and shifted slightly so that nothing aligns. In turn, you can make heads or tails as to what's happening. However, if you select File -> Refresh from my menubar (calls repaint() the same way) everything is repainted correctly. Any ideas?
    package dispatchBoard.DispatchBoard;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.sql.*;
    import javax.swing.JPanel;
    import sun.misc.Queue;
    public class DB_MainWindow extends JPanel implements MouseListener{
         private static final long serialVersionUID = 1L;
         private int _xRes, _yRes;
         private int _techs;
         private String _dayOption, _monday, _tuesday, _wednesday, _thursday, _friday, _odbcName, _databaseName, _currYear;
         private String[] _months;
         private Tech _myTechList;
         private Font _defaultFont;
         DB_Frame _mainFrame;
         private Calendar cal = new GregorianCalendar();
         public DB_MainWindow(String _resolution, String optionString, String ofTechs, DB_Frame frame, String _odbc, String _database, String _year)
              _xRes = Integer.valueOf(_resolution.substring(0, findCharPosition(_resolution, 'x'))).intValue() - 5;
              _yRes = Integer.valueOf(_resolution.substring(findCharPosition(_resolution, 'x')+1)).intValue() - 30;
              _techs = Integer.valueOf(ofTechs).intValue();
              _dayOption = optionString;
              _mainFrame = frame;
              _odbcName = _odbc;
              _databaseName = _database;
              _currYear = _year;
              setDaysFiveStraight();
              System.out.println(_xRes + " " + _yRes);
              this.setBackground(Color.GRAY);
              this.setPreferredSize(new Dimension(_xRes,_yRes));
              this.addMouseListener(this);
         public void paint(Graphics g)
              _myTechList = null;
              int _spacing = 0;
              int _spacing2 = 0;
              g.setColor(Color.BLACK);
              g.drawLine(60,0,60,_yRes);
              _defaultFont =g.getFont();
              //draw tech barriers
              for (int i = 1; i < _techs+1; i ++)
                   _spacing = _yRes / (_techs+1);
                   g.drawLine(0, _spacing*i, 1366, _spacing*i);
              //draw day barriers
              for (int j = 1; j < 5; j++)
                   _spacing2 = (_xRes-60) / 5;
                   g.drawLine(_spacing2*j + 60, 0, _spacing2*j + 60, 768);
              int _curPos = 60, _timePos = 0;
              int _time[] = {8,9,10,11,12,1,2,3,4,5};
              for (int k = 0; k < 5; k++)
                   _curPos = 60+(k*_spacing2);
                   for (int l = 0; l < 9; l++)
                        g.drawLine( _curPos + (l*(_spacing2/9)), 0+_spacing, _curPos + (l*(_spacing2/9)), _yRes);
                        String _tempString = ""+_time[_timePos];
                        g.drawString(_tempString, _curPos + (l*(_spacing2/9)), _spacing);
                        _timePos++;
                   _timePos = 0;
              //draw graph labels
              System.out.println(_dayOption);
              g.drawString("TECHS", 10, _spacing);
              g.drawString("Monday "+_monday, 60+(_spacing2/2) - 23, _spacing/2);
              g.drawString("Tuesday "+_tuesday, 60+_spacing2+(_spacing2/2) - 26, _spacing/2);
              g.drawString("Wednesday "+_wednesday, 60+2*_spacing2+(_spacing2/2) - 33, _spacing/2);
              g.drawString("Thursday "+_thursday, 60+3*_spacing2+(_spacing2/2) - 28, _spacing/2);
              g.drawString("Friday "+_friday, 60+4*_spacing2+(_spacing2/2) - 25, _spacing/2);
               * At this point the default grid, including all labels, have been drawn on
               * the dispatch board.  Now, we have to fetch the data from the SQL server,
               * place it into some sort of form (possibly 2d array?!) and then print it out
               * on the board....
               * Here goes!
    //          this.addMouseMotionListener(this);
    //          g.drawRect(_mousePosition.x, _mousePosition.y, 10, 10);
              fillInTimes(g, _spacing, _spacing2);
         public void setDaysFiveStraight()
              if (_dayOption.equals(new String("work_week")))
                   _monday = new String("");
                   _tuesday = new String("");
                   _wednesday = new String("");
                   _thursday = new String("");
                   _friday = new String("");
                   String[] _months2 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
                   _months = _months2;
                    * Sunday = 1
                    * Monday = 2
                   System.out.println("DAY OF THE WEEK = "+cal.get(Calendar.DAY_OF_WEEK));
                   if (cal.get(Calendar.DAY_OF_WEEK) == 2)
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 3)
                   {     //tuesday
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        System.out.println("TUESDAY = "+_tuesday);
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 4)
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        //System.out.println("TUESDAY = "+_tuesday);
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 5)
                   {     //thursday
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 6)
                   {     //friday
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
         private void fillInTimes(Graphics g, int _spacing, int _spacing2) {
              // need to get the data first, building pre-defined array for test data...
              //****START REAL DATA LOAD****\\
    //          Calendar cal = new GregorianCalendar();
             try {
                 // Load the JDBC-ODBC bridge
                 Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
                 // specify the ODBC data source's URL
                 String url = "jdbc:odbc:"+_odbcName;
                 // connect
                 Connection con = DriverManager.getConnection(url,"sa",_currYear);
                 // create and execute a SELECT
                 Statement stmt = con.createStatement();
                 Statement stmt2 = con.createStatement();
                 ResultSet techList = stmt2.executeQuery("USE "+_databaseName+" SELECT Distinct(SV00301.Technician) from SV00301 join SV00115 on SV00301.Technician = SV00115.Technician where SV00115.SV_Inactive<>1");
                 // traverse through results
                 Tech temp;
                 int counter = 0;
                 while(techList.next())
                      if (_myTechList == null)
                           _myTechList = new Tech(techList.getString(1).trim());
                           System.out.println(_myTechList.getName());
                           counter++;
                      else if (!_myTechList.hasNext())
                           _myTechList.setNext(new Tech(techList.getString(1).trim()));
                           System.out.println(_myTechList.getNext().getName());
                           counter++;
                      else
                           temp = _myTechList.getNext();
                           while(temp.hasNext())
                                temp = temp.getNext();
                           temp.setNext(new Tech(techList.getString(1).trim()));
                           System.out.println(temp.getNext().getName());
                           counter++;
    //             printTechList();
                 String nextMonth, prevMonth;
                 if(cal.get(Calendar.MONTH)==11)
                      nextMonth=_months[0];
                 else
                      nextMonth = _months[cal.get(Calendar.MONTH)+1];
                 if(cal.get(Calendar.MONTH) == 0)
                      prevMonth = _months[11];
                 else
                      prevMonth = _months[cal.get(Calendar.MONTH)-1];
                 ResultSet rs = stmt.executeQuery
                 ("USE "+_databaseName+" SELECT * from SV00301 JOIN SV00300 on SV00300.Service_Call_ID = SV00301.Service_Call_ID JOIN SV00115 on SV00300.Technician = SV00115.Technician JOIN SV000805 on SV000805.Service_Call_ID = SV00301.Service_Call_ID and SV000805.Note_Service_Index='Description' where (Month(SV00301.Task_Date)="+_months[cal.get(Calendar.MONTH)]+" or Month(SV00301.Task_Date)="+prevMonth+" or Month(SV00301.Task_Date)="+nextMonth+") and SV00300.Status_of_Call='OPEN' and SV00115.SV_Inactive<>1");
                 System.out.println("USE "+_databaseName+" SELECT * from SV00301 JOIN SV00300 on SV00300.Service_Call_ID = SV00301.Service_Call_ID JOIN SV00115 on SV00300.Technician = SV00115.Technician JOIN SV000805 on SV000805.Service_Call_ID = SV00301.Service_Call_ID and SV000805.Note_Service_Index='Description' where (Month(SV00300.Date_of_Service_Call)="+_months[cal.get(Calendar.MONTH)]+" or Month(SV00300.Date_of_Service_Call)="+prevMonth+" or Month(SV00300.Date_of_Service_Call)="+nextMonth+") and SV00300.Status_of_Call='OPEN' and SV00115.SV_Inactive<>1");
                  while (rs.next()) {
                      // get current row values
                       String servicecallid = rs.getString(1).trim(),
                               tech = rs.getString(4).trim(),
                               rawDate = rs.getString(6).trim(),
                               startTime = rs.getString(7).trim(),
                               _length = rs.getString(9).trim(),
                               description = rs.getString(33).trim(),
                               customernumber = rs.getString(35).trim(),
                               custname = rs.getString(45).trim(),
                               location = rs.getString(46).trim(),
                               calltype = rs.getString(54).trim(),
                               notes = rs.getString(268).trim();   
    //                  String formattedDate = month+"/"+day+"/"+year;
    //                  System.out.println(formattedDate);
    //                  String tech = rs.getString(142).trim();
    //                  String rawDate = rs.getString(144);
                      System.out.println(rawDate);
                      String day = rawDate.substring(8,10);
                      String month = rawDate.substring(5,7);
                      String year = rawDate.substring(0,4);
                      formatNumber(day);
                      formatNumber(month);
    //                  startTime = rs.getString(145);
    //                  String _length = rs.getString(147);
                      int hour = Integer.valueOf(startTime.substring(11,13)).intValue();
                      String minute = startTime.substring(14,16);
                      int minutes = Integer.valueOf(minute).intValue();
                      minutes = minutes / 60;
                      double length = (Integer.valueOf(_length).intValue())/100;
                      // print values
                      //System.out.println ("Service_Call_ID = " + Surname);
                      if (hour!=0)
                           sortJob(new Job(servicecallid, custname, new MyDate(month,day,year), hour+minutes,length, description, customernumber, location, calltype, notes), _myTechList, tech);
                  // close statement and connection
                  stmt.close();
                  con.close();
                  catch (java.lang.Exception ex) {
                      ex.printStackTrace();
              //draw techs and blocks of jobs!!!!!
              //***TECHS***\\
             Tech _tempTech = new Tech("DOOKIE");
              int multiplier = 2;
              if (_myTechList.hasNext())
                   g.setColor(Color.BLACK);
                   _tempTech = _myTechList.getNext();
                   g.drawString(_myTechList.getName(),5,(_spacing)*multiplier);
                   System.out.println("printJobs(g, "+_myTechList.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
                   printJobs(g,_myTechList,multiplier, _spacing,_spacing2);
                   multiplier++;
              while(_tempTech.hasNext())
                   g.setColor(Color.BLACK);
                   g.drawString(_tempTech.getName(),5,(_spacing)*multiplier);
                   System.out.println("printJobs(g, "+_tempTech.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
                   printJobs(g,_tempTech,multiplier, _spacing,_spacing2);
                   multiplier++;
                   _tempTech = _tempTech.getNext();
              g.setColor(Color.BLACK);
              g.drawString(_tempTech.getName(),5,(_spacing)*multiplier);
              System.out.println("printJobs(g, "+_tempTech.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
              printJobs(g,_tempTech,multiplier, _spacing,_spacing2);
              //***TIME BLOCKS***\\\
         private void printTechList() {
              // TODO Auto-generated method stub
              boolean temp = !_myTechList.hasNext();
              Tech tempTech = _myTechList;
              System.out.println("BEGINNING TECH LIST PRINTOUT!!!!");
              while (tempTech.hasNext() || temp)
                   System.out.println(tempTech.getName());
                   if (temp)
                        temp = !temp;
                   else
                        tempTech = tempTech.getNext();
              System.out.println(tempTech.getName());
              System.out.println("END TECH LIST PRINTOUT!!!");
         private void formatNumber(String month) {
              // TODO Auto-generated method stub
              if (month.equals(new String("01")))
                   month = new String("1");
              else if (month.equals(new String("02")))
                   month = new String("2");
              else if (month.equals(new String("03")))
                   month = new String("3");
              else if (month.equals(new String("04")))
                   month = new String("4");
              else if (month.equals(new String("05")))
                   month = new String("5");
              else if (month.equals(new String("06")))
                   month = new String("6");
              else if (month.equals(new String("07")))
                   month = new String("7");
              else if (month.equals(new String("08")))
                   month = new String("8");
              else if (month.equals(new String("09")))
                   month = new String("9");
         private void printJobs(Graphics g, Tech techList, int multiplier, int _spacing, int _spacing2) {
              Job tempJob = techList.getJobs();
              boolean temp = false;
              if (tempJob != null)
              {     temp = !tempJob.hasNext();
              while (tempJob.hasNext() || temp)
                   g.setColor(Color.RED);
                   String _tempDate = new String(tempJob.getDate().toString());
    //               System.out.println("This job has date of: "+_tempDate);
                   int horizontalMultiplier = 0;
                   if (_tempDate.equals(_monday))
                        horizontalMultiplier = 0;
                   else if (_tempDate.equals(_tuesday))
                        horizontalMultiplier = 1;
                   else if (_tempDate.equals(_wednesday))
                        horizontalMultiplier = 2;
                   else if (_tempDate.equals(_thursday))
                        horizontalMultiplier = 3;
                   else if (_tempDate.equals(_friday))
                        horizontalMultiplier = 4;
                   else
                        horizontalMultiplier = 5;
    //               System.out.println("HorizontalMultiplier = "+horizontalMultiplier);
                   if (horizontalMultiplier !=5)
                        if (tempJob.getJobCallType().equals(new String("TM"))) g.setColor(new Color(0,255,0));
                        else if (tempJob.getJobCallType().equals(new String("SU"))) g.setColor(new Color(0,255,255));
                        else if (tempJob.getJobCallType().equals(new String("SPD"))) g.setColor(new Color(44,148,67));
                        else if (tempJob.getJobCallType().equals(new String("QUO"))) g.setColor(new Color(0,255,255));
                        else if (tempJob.getJobCallType().equals(new String("MCC"))) g.setColor(new Color(255,0,255));
                        else if (tempJob.getJobCallType().equals(new String("MC"))) g.setColor(new Color(128,0,255));
                        else if (tempJob.getJobCallType().equals(new String("CBS"))) g.setColor(new Color(0,0,255));
                        else if (tempJob.getJobCallType().equals(new String("AS"))) g.setColor(new Color(255,255,255));
                        else g.setColor(Color.red);
                        g.fillRect(/*START X*/(int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1),/*START Y*/_spacing*(multiplier-1)+1,/*LENGTH*/(int)(tempJob.getJobLength()*(_spacing2/9)-1),/*WIDTH*/_spacing-1);
                        System.out.println("g.fillRect("+((int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1))+","+(_spacing*(multiplier-1)+1)+","+((int)(tempJob.getJobLength()*(_spacing2/9)-1))+","+(_spacing-1)+") :: Multiplier = "+multiplier+" :: JOB NAME = "+tempJob.getJobName()+" :: JOB NUMBER = "+tempJob.getJobNumber());
                        g.setColor(Color.BLACK);
                        g.setFont(new Font("Monofonto", Font.PLAIN, 22));
                        if ((int)(tempJob.getJobLength()*(_spacing2/9)-1) >0)
                             g.drawString(formatStringLength(tempJob.getJobName().toUpperCase(), tempJob.getJobLength()), (int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1), (_spacing*(multiplier)+1)-_spacing/2+5);
                        g.setFont(_defaultFont);
                        if (!temp)
                             tempJob = tempJob.getNext();
                             if (tempJob.hasNext() == false)
                                  temp = true;
                        else
                             temp = !temp;
                   else
                        System.out.println("*g.fillRect("+((int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1))+","+(_spacing*(multiplier-1)+1)+","+((int)(tempJob.getJobLength()*(_spacing2/9)-1))+","+(_spacing-1)+") :: Multiplier = "+multiplier+" :: JOB NAME = "+tempJob.getJobName()+" :: JOB NUMBER = "+tempJob.getJobNumber());
                        if (!temp)
                             tempJob = tempJob.getNext();
                             if (tempJob.hasNext() == false)
                                  temp = true;
                        else
                             temp = !temp;
         //     g.fillRect((int)(60+(tempJob.getStarTime()-8)*(_spacing2/9)+1),_spacing*(multiplier-1)+1,(int)(tempJob.getJobLength()*(_spacing2/9)-1),_spacing-1);
         private String formatStringLength(String string, double jobLength) {
              // TODO Auto-generated method stub
              if (jobLength*3>string.length())
                   return string;
              return string.substring(0, new Double(jobLength*3).intValue());
         private void sortJob(Job job, Tech techList, String techName) {
              Tech _tempTech2;
              if (techName.equals(techList.getName()))
                   techList.insertJob(job);
                   System.out.println("ADDED " + job.getJobName() +" TO " + techName);
              else
                   _tempTech2 = techList.getNext();
                   while (!_tempTech2.getName().equals(techName) && _tempTech2.hasNext())
                        _tempTech2 = _tempTech2.getNext();
    //                    System.out.println(_tempTech2.getName()+" vs. " + techName);
                   if (_tempTech2.getName().equals(techName))
                        _tempTech2.insertJob(job);
                        System.out.println("ADDED " + job.getJobName() +" TO " + techName);
                   else
                        System.out.println("TECH NAME: "+_tempTech2.getName()+" NOT FOUND :: COULD NOT INSERT JOB");
         private int findCharPosition(String _resolution2, char c) {
              // TODO Auto-generated method stub
              for (int i = 0; i < _resolution2.length(); i++)
                   if (_resolution2.charAt(i) == c)
                        return i;
              return 0;
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
              System.out.println("Mouse clicked at coordinates: "+arg0.getX()+", "+arg0.getY()+"\nAttempting to intelligently find the job number");
               * Find the tech
              int techNum = arg0.getY()/(_yRes / (_techs+1));
              String techName= new String("");
              int counter = 0;
              Tech temp = _myTechList;
              boolean found = true;
              while(temp.hasNext() && found)
                   counter++;
                   if (counter == techNum)
                        techName = temp.getName();
                        found = false;
                   else
                        temp = temp.getNext();
              System.out.println("The "+techNum+"th tech was selected... which means you clicked "+techName);
               * Find the day
              int day = (arg0.getX()-60)/(0 + ((_xRes-60)/5));
              String days[] = {_monday, _tuesday, _wednesday, _thursday, _friday};
              System.out.println("The day you chose was "+days[day]);
               * Find the time
              int blocksIn = ((arg0.getX()-60)/(((_xRes-60)/5)/9))%9;
              System.out.println(blocksIn+" blocks inward!!!!");
               * Find the job
               *           - temp is already initialized to the current tech!!
              System.out.println(temp.getName()+" has "+temp.getNumberOfJobs()+" jobs");
              Job current = temp.getJobs();
              Queue jobQueue = new Queue();
              boolean first = true;
              while(current.hasNext() || first)
                   if(current.getDate().toString().equals(days[day]))
                        jobQueue.enqueue(current);
                        System.out.println("Queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
                        if (first)
                             first = false;
                             current = current.getNext();
                        else
                             current = current.getNext();
                   else
                        System.out.println("Did not queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
                        if (first)
                             first = false;
                             current = current.getNext();
                        else
                             current = current.getNext();
              if(current.getDate().toString().equals(days[day]))
                   jobQueue.enqueue(current);
                   System.out.println("Queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
              else
                   System.out.println("Did not queue the job on "+current.getDate().toString()+"::"+current.getJobNumber());
              blocksIn+=8;
              while(!jobQueue.isEmpty())
                   try {
                         * Get a job off the queue... now check the times
                        Job dqJob = (Job)jobQueue.dequeue();
                        System.out.println(dqJob.getStarTime()+"<="+blocksIn +" && "+(dqJob.getStarTime()+dqJob.getJobLength()-1)+">="+blocksIn+" :: "+dqJob.getJobName());
                        if (dqJob.getStarTime()<=blocksIn && dqJob.getStarTime()+dqJob.getJobLength()-1>=blocksIn)
                             System.out.println("MONEY!!!! Found job: "+dqJob.getJobName());
                             new JobDisplayer(dqJob, _xRes, _yRes);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseClicked(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void nextDay() {
              // TODO Auto-generated method stub
              if (_dayOption.equals(new String("work_week")))
                   cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+7);
                   setDaysFiveStraight();
              this.repaint();
         public void prevDay() {
              // TODO Auto-generated method stub
              if (_dayOption.equals(new String("work_week")))
                   cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-7);
                   setDaysFiveStraight();
                   this.repaint();
              this.repaint();
    }Sorry for the huge chunk of code.
    Thanks in advance,
    Jeff

    Sorry for the huge chunk of code.
    Mm, yes, I'm far too lazy to read all that.
    But you should be overriding paintComponent(), not paint().
    http://www.google.co.uk/search?hl=en&q=java+swing+painting&btnG=Google+Search&meta=
    I've not bothered to work out from that pile of magic numbers exactly what you're tring to draw but is it not something that JTable would happily do?

  • JTable text alignment issues when using JPanel as custom TableCellRenderer

    Hi there,
    I'm having some difficulty with text alignment/border issues when using a custom TableCellRenderer. I'm using a JPanel with GroupLayout (although I've also tried others like FlowLayout), and I can't seem to get label text within the JPanel to align properly with the other cells in the table. The text inside my 'panel' cell is shifted downward. If I use the code from the DefaultTableCellRenderer to set the border when the cell receives focus, the problem gets worse as the text shifts when the new border is applied to the panel upon cell selection. Here's an SSCCE to demonstrate:
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.EventQueue;
    import javax.swing.GroupLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.border.Border;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import sun.swing.DefaultLookup;
    public class TableCellPanelTest extends JFrame {
      private class PanelRenderer extends JPanel implements TableCellRenderer {
        private JLabel label = new JLabel();
        public PanelRenderer() {
          GroupLayout layout = new GroupLayout(this);
          layout.setHorizontalGroup(layout.createParallelGroup().addComponent(label));
          layout.setVerticalGroup(layout.createParallelGroup().addComponent(label));
          setLayout(layout);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
          if (isSelected) {
            setBackground(table.getSelectionBackground());
          } else {
            setBackground(table.getBackground());
          // Border section taken from DefaultTableCellRenderer
          if (hasFocus) {
            Border border = null;
            if (isSelected) {
              border = DefaultLookup.getBorder(this, ui, "Table.focusSelectedCellHighlightBorder");
            if (border == null) {
              border = DefaultLookup.getBorder(this, ui, "Table.focusCellHighlightBorder");
            setBorder(border);
            if (!isSelected && table.isCellEditable(row, column)) {
              Color col;
              col = DefaultLookup.getColor(this, ui, "Table.focusCellForeground");
              if (col != null) {
                super.setForeground(col);
              col = DefaultLookup.getColor(this, ui, "Table.focusCellBackground");
              if (col != null) {
                super.setBackground(col);
          } else {
            setBorder(null /*getNoFocusBorder()*/);
          // Set up our label
          label.setText(value.toString());
          label.setFont(table.getFont());
          return this;
      public TableCellPanelTest() {
        JTable table = new JTable(new Integer[][]{{1, 2, 3}, {4, 5, 6}}, new String[]{"A", "B", "C"});
        // set up a custom renderer on the first column
        TableColumn firstColumn = table.getColumnModel().getColumn(0);
        firstColumn.setCellRenderer(new PanelRenderer());
        getContentPane().add(table);
        pack();
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            new TableCellPanelTest().setVisible(true);
    }There are basically two problems:
    1) When first run, the text in the custom renderer column is shifted downward slightly.
    2) Once a cell in the column is selected, it shifts down even farther.
    I'd really appreciate any help in figuring out what's up!
    Thanks!

    1) LayoutManagers need to take the border into account so the label is placed at (1,1) while labels just start at (0,0) of the cell rect. Also the layout manager tend not to shrink component below their minimum size. Setting the labels minimum size to (0,0) seems to get the same effect in your example. Doing the same for maximum size helps if you set the row height for the JTable larger. Easier might be to use BorderLayout which ignores min/max for center (and min/max height for west/east, etc).
    2) DefaultTableCellRenderer uses a 1px border if the UI no focus border is null, you don't.
    3) Include a setDefaultCloseOperation is a SSCCE please. I think I've got a hunderd test programs running now :P.

  • Right aligning a label in a jpanel

    Hey not quite sure how to do this.
    public MenuApp()
    super("Hello World!");
    setSize(400, 300);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              Container cp = getContentPane();
              JMenu mnuFile = new JMenu("File");
              mnuFile.add(f_milFF);
              mnuFile.add(f_misTF);
    mnuFile.addSeparator();
    mnuFile.add(f_miExit);
              JMenu mnuEdit = new JMenu("Edit");
              mnuEdit.add(f_misNS);
              mnuEdit.addSeparator();
              mnuEdit.add(f_miclear);
    JMenuBar mb = new JMenuBar();
    mb.add(mnuFile);
              mb.add(mnuEdit);
    setJMenuBar(mb);
              JPanel pan = new JPanel();
              pan.setLayout(new GridLayout(1,2));
              pan.add(f_lblNumberOfStudents);                    JScrollPane lstScroll = new JScrollPane(f_lstStudents);
              lstScroll.setBorder(BorderFactory.createEtchedBorder());
              cp.setLayout(new BorderLayout());
    get this in mid cp.add(pan, BorderLayout.SOUTH);

    i assume you need help with JLabel alone
    JLabel f_lblNumberOfStudents;
    f_lblNumberOfStudents = new JLabel("Align test",JLabel.RIGHT);
    pan.add(f_lblNumberOfStudents);
    By the way i just had a big naming convention guideline...
    http://forum.java.sun.com/thread.jsp?forum=54&thread=459121&start=15&range=15&hilite=false&q=

  • Tabs Won't Work Right Aligned JPanel

    Hello
    I'm tring to setup a JPanel using a style object for formating, JPanel.setLogicalStyle(styleimade);, and I haver everything working beautifuly for a left alligned panel, but when I attempt to work with tabs on a panel that is right aligned, StyleConstants.setAlignment(styleimade, ALIGN_RIGHT), I can't seem to get tabs to work at all. Using StyleConstants.setTabSet(styleimade, atabsetimade) to set the tabs. When I make my tabset it doesn't matter what I have my tabstops set to the indention doesn't change. When I set the alignment back to left, the tabs start to work.
    When I try to do a search on documentation I naturally get a huge list of tabpanels, and can't seeem to find anything on this particular subject.
    Any suggestions or links to other forums would be a huge help.
    Thank you in advance!

    Ok, I had thought it meant I need to be able to compile and execture the code.
    Here it is...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.lang.Object.*;
    import java.util.*;
    //enxtends JFrame because it is a window, Implements KeyListener, ActionListener
    //so it can accept keyed input.
    public class testGUI extends JFrame {
        //stores the device that this window is using to display itself.
        GraphicsDevice device;
        //both are used to store the height and width of the screen
        int ScreenHeight;
        int ScreenWidth;
        //create a bool to hold if the screen should be fullscreen or not
        boolean fullscreen = true;
        //create colors to hold default colors
        Color Blue;
        Color Orange;
        Color Black;
        //create text panels that will be displayed on the screen
        JTextPane TopLeft;
        StyledDocument DocTopLeft;
        //pass a graphics device so it knows which screen to take, the number of the
        //current display so it knows what to name the window, the height of the
        //current screen, and width so it can use that to set objects
        public testGUI(GraphicsDevice device, String NumberOfDisplay,
                              int WindowHeight, int WindowWidth) {
            //set the name and size of the screen.
            super("Screen " + NumberOfDisplay);
         setSize(800,600);
            //set the screenheight and width data types
            ScreenHeight = WindowHeight;
            ScreenWidth = WindowWidth;
            //start up everything is Design view
            //initComponents();
            //set the screen up
            setScreen();
            //setLocationRelativeTo nothing so the screen will center
         setLocationRelativeTo(null);
            //set the device for this window to the device passed to the class
            this.device = device;
            //when a close is initiated, exit
         setDefaultCloseOperation(EXIT_ON_CLOSE);    
            //as default show the screen
            setVisible(true);
        }//end default constructor
        public void setScreen() {
            //What happens when the X is clicked
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            //set the colors for this window
            Blue = new Color(0, 0, 204);
            Orange = new Color(244, 143, 0);
            Black = new Color(0, 0, 0);
            //change backgruond color of screen
            this.setBackground(Orange);
            this.getContentPane().setBackground(Orange);
    //....................................................Settings for TopLeft Pane
            //create the setup the panel
            TopLeft = new JTextPane();
            TopLeft.setEditable(false);
            TopLeft.setFocusable(false);
            TopLeft.setBackground(Orange);
            TopLeft.setPreferredSize(new java.awt.Dimension(((int) (ScreenWidth * .6)), ((int) (ScreenHeight * .6))));
            TopLeft.setDisabledTextColor(Black);
            //set Document to TopLeft
            DocTopLeft = TopLeft.getStyledDocument();
            //Create a list to hold tabstops
            java.util.List TabListLeft = new ArrayList();
            //create a tabstop, using the screen as a reference
            TabStop tstop = new TabStop(((int) (ScreenWidth * .25)), TabStop.ALIGN_CENTER, TabStop.LEAD_NONE);
            TabListLeft.add(tstop);
            //create another tab stop
            tstop = new TabStop(((int) (ScreenWidth * .33)), TabStop.ALIGN_CENTER, TabStop.LEAD_NONE);
            TabListLeft.add(tstop);
            //creating tab stop
            tstop = new TabStop(((int) (ScreenWidth * .41)), TabStop.ALIGN_CENTER, TabStop.LEAD_NONE);
            TabListLeft.add(tstop);
            //create a tab
            tstop = new TabStop(((int) (ScreenWidth * .49)), TabStop.ALIGN_CENTER, TabStop.LEAD_NONE);
            TabListLeft.add(tstop);       
            // Create a tab set from the tab stops that were made above
            TabStop[] TabStopsLeft = (TabStop[])TabListLeft.toArray(new TabStop[0]);
            TabSet TabsLeft = new TabSet(TabStopsLeft);
            // Add the tab set to the logical style;
            // the logical style is inherited by all paragraphs
            Style StyleTopLeft = TopLeft.getLogicalStyle();
            StyleConstants.setAlignment(StyleTopLeft, StyleConstants.ALIGN_RIGHT);
            StyleConstants.setTabSet(StyleTopLeft, TabsLeft);
            TopLeft.setLogicalStyle(StyleTopLeft);
            //add styles to document, in this case, it is just fonts formating
            addStylesToDocument(DocTopLeft);
            //insert text into the JPanels
            try{
                    //start with text pane at top left
                    DocTopLeft.insertString(TopLeft.getCaretPosition(), "Test", DocTopLeft.getStyle("titles"));
                    DocTopLeft.insertString(TopLeft.getCaretPosition(), ("\n\t" + "test\ttest\ttest"), DocTopLeft.getStyle("maintext"));
                    DocTopLeft.insertString(TopLeft.getCaretPosition(), "\n Test", DocTopLeft.getStyle("subtitles"));
                    DocTopLeft.insertString(TopLeft.getCaretPosition(), ("\t" + "test\ttest"), DocTopLeft.getStyle("maintext"));
                    }//end of try block for string insertion
            //I know I'm cheap there is no exception catch here
            //but the user doesn't edit anything so how can it be at the wrong location?!
            catch(Exception e) { }       
            //Make a layout that is based on things added to it
            GroupLayout layout = new GroupLayout(getContentPane());
            //set the layout for MenuDisplayGUI to the layout created above
            getContentPane().setLayout(layout);
            //Left and right                                    left and right
            layout.setHorizontalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(layout.createParallelGroup()
                    //create a sequential group that will hold all text boxes
                    .addGroup(layout.createSequentialGroup()
                        //create a paralle group to hold everyting on the left
                        .addGroup(layout.createParallelGroup()
                            .addComponent(TopLeft)
                            )//end of parallel group holding everything on left of screen
                        //.addContainerGap(1, Short.MAX_VALUE)
                    )//end of parallel group holding everything horizontally
            ));//close of layout.setHorizontalGroup
            //UP AND DOWN!!!                                      UP AND DOWN
            layout.setVerticalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    //create a sequential group to contain the items vertically
                    .addGroup(layout.createSequentialGroup() 
                        //create a paralle group to hold the items at the top of the screen
                        .addGroup(layout.createParallelGroup()
                            //add the item at the top left
                            .addComponent(TopLeft)
                            )//end of parallel group holding the two top items
                            //.addContainerGap(1, Short.MAX_VALUE)
                        )//end of sequential group holding everything vertically
            );//close of setVerticalGroup
            pack();
        }//end member function setScreen
        protected void addStylesToDocument(StyledDocument doc) {
            //create the defualt style that all other styles will build off of
            Style def = StyleContext.getDefaultStyleContext().
                            getStyle(StyleContext.DEFAULT_STYLE);
            //create the baseline for your style type
            Style regular = doc.addStyle("regular", def);
            StyleConstants.setFontFamily(def, "Sans");
            StyleConstants.setBold(def, true);
            //create a style used for titles, set the font
            Style titles = doc.addStyle("titles", regular);
            StyleConstants.setFontSize(titles, ((int) (ScreenWidth * .05)));
            StyleConstants.setForeground(titles, Blue);
            //create a style for subtitles
            Style subtitles = doc.addStyle("subtitles", regular);
            StyleConstants.setFontSize(subtitles, ((int) (ScreenWidth * .025)));
            //create a style for all of the rest of the text
            Style maintext = doc.addStyle("maintext", regular);
            StyleConstants.setFontSize(maintext, ((int) (ScreenHeight * .025)));
        }//end of member class addStyleToDocument   
        /** 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.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            pack();
        }// </editor-fold>                       
        * @param args the command line arguments
    public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    }//end try block
                    catch (Exception ex) {
                            System.out.println(ex);
                    }//end catch block
                    //get the graphics enviroment for this local computer
                    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
                    //create an array of graphics devices for all the "screen devices"
                    //in the env Graphics enviroment
              GraphicsDevice[] devices = env.getScreenDevices();
                    //create an integer for looping
                    int loop = 0;
                    //create a vector to hold multipe MenuDisplayGuis for systems
                    //that use multiple screen
                    Vector DisplayWindows;
                    DisplayWindows = new Vector();
                    //create a display mode which will later pass the height
                    //and width of the window to the MenuDisplayGUI object
                    DisplayMode DM;
                    //loop through all of the display devices on the local computer
                    //create a window for each screen
                    while( loop < devices.length ) {
                        //change the displaymode to the current display mode
                        DM = devices[loop].getDisplayMode();
                        //put a MenuDisplayGUI Window into the DisplyWindows vector
                        //for each display device that is on the computer. Pass the
                        //current iteration in this loop to the MenuDisplayGUI
                        //that is being created so it can name itself according to
                        //number, send the screen height and width to handle
                        //position of objects.
                        DisplayWindows.addElement(new testGUI(devices[loop],
                                                  String.valueOf(loop + 1),
                                                  DM.getHeight(), DM.getWidth()));
                        //iterate the loop
                        loop++;
                    }//end while loop
                }//end run block
        }//end static main
    }

  • Alignment of JPanel

    Hi,
    How can I make all the components in a JPanel to align to the right??
    I tried to use pnl.setAlignmentX(Right) and it doesn't work!
    thanks.

    First of all you question is not very detailed. Are you trying to align a row of buttons to the right of a panel or are you trying to align a vertical list of component to the right in a panel.
    The answer will be different depending on your situation. If the first case your would use a FlowLayout and set the aligment of the Layout, in the second case you would probably use a BoxLayout and set the alignment of each individual component. See this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]Using Layout Managers.
    I tried to use pnl.setAlignmentX(Right) and it doesn't work!You don't set alignment of the panel you set the alignment on the components being added to the panel. Sometimes this suggestion is used, sometimes it isn't.

  • How to activate left alignment with Jpanels??

    Hello
    Please what is wrong. I cannot get left alignment activated. Otherwise panel appear nicely on screen. Here are the main parts of code:
    public void addComponentToPane(Container allComponents) throws IOException {
    allComponents.setLayout(new BoxLayout(allComponents, BoxLayout.PAGE_AXIS));
       panel_introduction.setAlignmentX(JPanel.LEFT_ALIGNMENT);
    allComponents.add(panel_introduction);
       allComponents.setVisible(true);
    }Edited by: wonderful123 on Oct 14, 2007 10:26 AM

    Alignment in a BoxLayout can be more complicated than it appears. Posting 4 lines of code does not give us enough information.
    So read the Swing tutorial on "How to Use Box Layout" for an explanation and examples of how alignment in a Box Layout works.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    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.

  • Align columns in separate JPanels

    Hello all,
    I am having a problem aligning columns of JLabels in separate JPanels. I'm using GridBagLayout.
    Basically, I have multiple JPanels on a JFrame, they display in a tabular column, but I can't get each JPanel to align with the columns of the JPanel above it.
    I've also tried using the SpringLayout, but that's only good if I already know how big each of my columns are. (the data is dynamically loade). And I MUST use multiple JPanels because I can have THOUSANDS of labels and JPanel only limits to 512 components per panel.
    So, how to do this? I will award duke dollars to anyone who can help me out - I will also be forever grateful. Below is sample code:
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class AlignTest extends JPanel
         public void buildWindow()
              Container contentPane = this;
              GridBagLayout gb = new GridBagLayout();
              contentPane.setLayout(gb);
              GridBagConstraints gc = new GridBagConstraints();
              gc.fill=GridBagConstraints.BOTH;
              gc.anchor=GridBagConstraints.NORTHWEST;
              GridBagConstraints gc2 = new GridBagConstraints(); // for use with gb2
              gc2.insets=new Insets(2,4,2,4);
              int i = 0, y = 0;
              Color color[] = { Color.white, Color.yellow };
              String name[] = { "dog", "cat", "bunny", "chicken" };
              String name2[] = { "really long", "short", "joe", "z" };
              String name3[] = { "b", "cdefghigklmnop", "D", "jflajfajlaskjfaljfsaljf" };
              for (i = 0, y = 1; i < 4; i++, y++)
                   JPanel pane = new JPanel();
                   GridBagLayout gb2=new GridBagLayout();
                   pane.setLayout(gb2);
                   pane.setBorder(BorderFactory.createLineBorder(new Color(0, 56, 107)));
                   JLabel lab=new JLabel(name);
                   gc2.anchor=GridBagConstraints.NORTHWEST;
                   gc2.gridx=0; gc2.gridy=0;
                   gc2.weightx=.5;
                   gb2.setConstraints(lab, gc2);
                   pane.add(lab);
                   lab=new JLabel(name2[i]);
                   gc2.gridx++;
                   gc2.weightx=.3;
                   gb2.setConstraints(lab, gc2);
                   pane.add(lab);
                   lab=new JLabel(name3[i]);
                   gc2.anchor=GridBagConstraints.NORTHEAST;
                   gc2.gridx++;
                   gc2.weightx=.2;
                   gb2.setConstraints(lab, gc2);
                   pane.add(lab);
                   gc.gridx=0; gc.gridy=y;
                   gb.setConstraints(pane, gc);
                   contentPane.add(pane);
              } // end printing rows
         } // end buildWindow
         /** unit testing - makes sure this class works
         * by itself.
         public static void main(String[] args)
              JFrame frame = new JFrame("Test of Row toggle");
              frame.addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
              AlignTest mainPane = new AlignTest();
              mainPane.buildWindow();
              frame.getContentPane().add(mainPane);
              //frame.pack();
              frame.setSize(200, 200);
              frame.setVisible(true);
         } // end main unit test
    } // end AlignTest

    I got frustrated with layout managers too. My project looked very ugly when resizing, so I wrote my own layout manager. To write a layout manager you have to implement a few methods. Chief among them is layoutContainer.
    My case is a little different than yours because the number of components I needed to layout is fixed. JTable may be a good bet for you because you can adjust the column widths after the fact. The irritant is that any resizing causes the JTables to revert back to their equidistant spacing. The way around that is to force ALL repeat ALL table columns to have a preferred width. Notice how I did this in the last few lines of the layoutContainer method.
    * Adds the specified component with the specified name to
    * the layout.
    * @param name the component name
    * @param comp the component to be added
    public void addLayoutComponent(String name, Component comp){
    * Removes the specified component from the layout.
    * @param comp the component to be removed
    public void removeLayoutComponent(Component comp){;}
    * Calculates the preferred size dimensions for the specified
    * panel given the components in the specified parent container.
    * @param parent the component to be laid out
    * @see #minimumLayoutSize
    public Dimension preferredLayoutSize(Container parent){return this.SIZE_TOTAL_MIN;}
    * Calculates the minimum size dimensions for the specified
    * panel given the components in the specified parent container.
    * @param parent the component to be laid out
    * @see #preferredLayoutSize
    public Dimension minimumLayoutSize(Container parent){return this.SIZE_TOTAL_MIN;}
    * Calculates the maximum size dimensions for the specified
    * panel given the components in the specified parent container.
    * @param parent the component to be laid out
    * @see #preferredLayoutSize
    public Dimension maximumLayoutSize(Container parent){return maxLayoutSize;}
    public void layoutContainer(Container target) {
    synchronized (target.getTreeLock()) {
    //Get the target size
    Dimension dTgt = target.getSize();
    int top[] = new int[6];
    int left[] = new int[6];
    int width[] = new int[6];
    int height[] = new int[6];
    height[5]=5*SIZE_BUTTON_MIN.height;
    height[4]=4*SIZE_BUTTON_MIN.height+29;
    height[3]=21;
    height[2]=3*SIZE_BUTTON_MIN.height+29;
    height[1]=dTgt.height-height[5]-height[2];
    height[0]=height[1];
    width[0]=(orientation==NO_BANNER) ? 0 : this.imageLogo.getIconWidth()+8;
    width[1]=dTgt.width-width[0];
    width[2]=dTgt.width;
    width[3]= width[4]=(dTgt.width << 2)/9;
    width[5]= dTgt.width-width[4];
    top[5]=top[3]=dTgt.height-height[5];
    top[4]=dTgt.height-height[4];
    top[2]=top[5]=height[2];
    top[0]=top[1]=0;
    top[2]=dTgt.height-429;
    top[3]=top[5]=dTgt.height-250;
    top[4]=dTgt.height-229;
    left[0]=left[2]=left[3]=left[4]=0;
    left[1]=width[0];
    left[5]=dTgt.width-width[5];
    if (orientation == LogoAndMessage.HORIZONTAL) {
    width[0]=dTgt.width;
    height[0]= this.imageLogo.getIconHeight()+8;
    left[1]=0;
    width[1]=dTgt.width;
    top[1]=height[0];
    height[1]-=height[0];
    this.sizeButton.width = dTgt.width/9;
    //Try to keep column[0] (step) the same size as the user left it
    int w = this.jTableLog.getColumnModel().getColumn(0).getWidth();
    this.jTableLog.getColumnModel().getColumn(0).setPreferredWidth(w);
    //Keep track of the remaining space
    int wOthers = width[1]-w;
    //Try to keep column[1] (name) the same size as the user left it
    w = this.jTableLog.getColumnModel().getColumn(1).getWidth();
    this.jTableLog.getColumnModel().getColumn(1).setPreferredWidth(w);
    wOthers -= w;
    //Try to keep column[3] (operator) the same size as the user left it
    w = this.jTableLog.getColumnModel().getColumn(3).getWidth();
    this.jTableLog.getColumnModel().getColumn(3).setPreferredWidth(w);
    wOthers -= w;
    //Divide the remaining space between columns 2 and 4 (value)
    wOthers >>= 1;
    this.jTableLog.getColumnModel().getColumn(2).setPreferredWidth(wOthers);
    this.jTableLog.getColumnModel().getColumn(4).setPreferredWidth(wOthers);
    //Try to keep column[0] (name) the same size as the user left it
    w = this.jTableStack.getColumnModel().getColumn(0).getWidth();
    this.jTableStack.getColumnModel().getColumn(0).setPreferredWidth(w);
    //We have this much to go
    wOthers = width[1]-w;
    //Try to keep column[1] (value) the same size as the user left it
    w = this.jTableStack.getColumnModel().getColumn(1).getWidth();
    this.jTableStack.getColumnModel().getColumn(1).setPreferredWidth(w);
    //Put all the remaining space into column[2] (expression)
    this.jTableStack.getColumnModel().getColumn(2).setPreferredWidth(wOthers - w);
    for (int p=0;p<getContentPane().getComponentCount();p++) {
    Component c = this.getContentPane().getComponent(p);
    c.setBounds(left[p],top[p],width[p],height[p]);
    Good Luck

  • Aligning text in a JPanel/JLabel

    Hi guyz,
    I have two text strings. One needs to be on the left edge and the other needs to be on the right edge. I created two JLabels and added these texts to them. Then, i used a FlowLayout to create a JPanel. But, all the time, they are being centered. I have mentioned the sizes of the labels also. Still, both the texts are being centered side by side. Here is the snippet of code. "increment" is an integer which identifies the Y position. This code is looped through for a particular no. of times.
           String conditionName = "";
           String conditionValue = "";
           conditionName = "<html>"+condition+"</html>";
           conditionValue = "<html>"+condValue+"</html>";
            JLabel conditionLabel = new JLabel();
            conditionLabel.setText(conditionName);
            conditionLabel.setBounds(5,increment,350,20);
            JLabel conditionValueLabel = new JLabel();
            conditionValueLabel.setText(conditionValue);
            conditionValueLabel.setBounds(360,increment,40,20);
            JPanel conditionsPanel = new JPanel();
            conditionsPanel.setBounds(5,increment,400,300);
            conditionsPanel.setLayout(new FlowLayout());
            conditionsPanel.add(conditionLabel);
            conditionsPanel.add(conditionValueLabel);Can anyone help?

    Hey Michael_Dunn,
    I have one more question. Though, the logic you gave worked, there is a small problem. I am actually looping through a number of times depending on the input list. So, if it is more than 5 times, then i get more than 5 pairs which is good enough to place them in a ScrollPane nicely. Where as if it is 2 or 3, then the whole scroll pane is being divided equally between those to place them which i don't want. I want to increment and place them one below other. That's why i used and increment variable whose initial value is "55". And each increment step is "25". But, it is not working. Can you tell me why? Here is the code i have used.
            JPanel panel = new JPanel(new GridLayout(1,2));
            JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
            JPanel p2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            p1.setBounds(5,increment,350,20);
            p1.setBounds(360,increment,40,20);
            p1.add(new JLabel("Hello",JLabel.LEFT));
            p2.add(new JLabel("World",JLabel.RIGHT));
            panel.setBounds(5,increment,400,300);
            panel.add(p1);
            panel.add(p2);

  • How to make a JPanel containing buttons  take up the width of the window?

    I'm creating a GUI and I have a button group that I want to be the width of the window. I have another JPanel on the same window that doesn't have a button group in it and it takes up the width of the window. I don't think I'm doing anything differently creating the two, but I need consistency.
    The best way I can explain this is with code, so I created an example of what I am doing here:
    import java.awt.*;
    import javax.swing.*;
    public class test extends JFrame {
         public test() {
              JPanel win = new JPanel();
              JPanel buttonsPanel = new JPanel();
              JPanel statusPanel = new JPanel();
              win.setLayout(new BoxLayout(win, BoxLayout.Y_AXIS));
              buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.Y_AXIS));
              statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.Y_AXIS));
    //          createRadioButtonsPanel
              ButtonGroup buttons = new ButtonGroup();
              JRadioButton currentMap = new JRadioButton("option1", true);
              JRadioButton newMap = new JRadioButton("option2");
              JRadioButton noMap = new JRadioButton("option3");
              buttons.add(currentMap);
              buttons.add(newMap);
              buttons.add(noMap);
              buttonsPanel.add(currentMap);
              buttonsPanel.add(newMap);
              buttonsPanel.add(noMap);
              buttonsPanel.setBorder(
                        BorderFactory.createTitledBorder("Create: "));
    //           createStatusPanel
              JLabel statusLabel = new JLabel("Loading...");
              statusLabel.setBorder(BorderFactory.createLoweredBevelBorder());
              statusLabel.setPreferredSize(new Dimension(400,20));
              statusLabel.setMinimumSize(new Dimension(400,20));
              statusLabel.setMaximumSize(new Dimension(400,20));
              statusPanel.add(statusLabel);
              JPanel statusButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              JButton pauseSearch = new JButton("Pause");
              JButton cancelSearch = new JButton("Cancel");
              statusButtons.add(pauseSearch);
              statusButtons.add(cancelSearch);
              statusPanel.add(statusButtons);
              statusPanel.setBorder(BorderFactory.createTitledBorder("Status: "));
              win.add(buttonsPanel);
              win.add(statusPanel);
              getContentPane().add(win);
              pack();
              setVisible(true);
         public static void main(String args[]) {
              test s = new test();
    }When I compile and run this class I get this window:
    http://img136.imageshack.us/img136/1538/exampleek5.png
    You see how on the bottom, "Status" JPanel takes up the entire width of the window? When the window is resized, the border is also resized. I would love to have the top "Create" JPanel have the same behavior. How do I do this?
    Thanks in advance!

    It can get confusing when using the BoxLayout. The box layout takes into consideration the X alignment of the components as well as the minimum and maximum lengths.
    So I suggest you read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html]How to Use Box Layout for examples and explanations on how these values are used in the layout process.
    It may be easier to use a BorderLayout for the high level layout manger, since it will resize a components width when added to the NORTH, CENTER or SOUTH.

  • Netbeans: adding to jPanel via code after init (jFreeChart)

    This will be my second post. Many thanks to those who replied to my first questions.
    I am using netbeans 5.5
    I am attempting to run the following jFreeChart demo but in netbeans.
    Original demo located here: http://www.java2s.com/Code/Java/Chart/JFreeChartPieChartDemo7.htm
    Instead of programically creating the jPanel like the demo does, i would like to do it using the netbeans GUI and then add the code to create the jFreeChart.
    In netbeans i create a new project, create a new jFrame and place a new jPanel on the form (keeping the variable name jPanel1) as illustrated below:
    * MainForm.java
    * Created on June 28, 2007, 1:48 PM
    package mypkg;
    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.ChartPanel;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.plot.PiePlot;
    import org.jfree.chart.plot.PiePlot3D;
    import org.jfree.data.general.DefaultPieDataset;
    import org.jfree.ui.ApplicationFrame;
    import org.jfree.ui.RefineryUtilities;
    * @author  me
    public class MainForm extends javax.swing.JFrame {
        /** Creates new form MainForm */
        public MainForm() {
            initComponents();
        /** Netbeans Auto-Generated Code goes here which I have omitted */                       
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainForm().setVisible(true);
        private void CreateChart() {
            DefaultPieDataset dataset = new DefaultPieDataset();
            dataset.setValue("Section 1", 23.3);
            dataset.setValue("Section 2", 56.5);
            dataset.setValue("Section 3", 43.3);
            dataset.setValue("Section 4", 11.1);
            JFreeChart chart3 = ChartFactory.createPieChart3D("Chart 3", dataset, false, false, false);
            PiePlot3D plot3 = (PiePlot3D) chart3.getPlot();
            plot3.setForegroundAlpha(0.6f);
            plot3.setCircular(true);
            jPanel1.add(new ChartPanel(chart3));
            jPanel1.validate();
        // Variables declaration - do not modify                    
        private javax.swing.JPanel jPanel1;
        // End of variables declaration                  
    }I then attempted to call the CreateChart() function in several places (in the MainForm() function, in the pre and post creation code properties of the jPanel's properties dialog in netbeans (as well as pre and post init in the same screen)) and nothing seems to work. the program compiles and the jFrame comes up but the chart does not show.
    If i run the example at the above noted link it runs fine in netbeans if i copy and paste the code directly, it just doesnt work when i try to get it to work through the netbeans GUI builder and the jPanel i create through it.
    Can any more advanced netbeans/java users lend me a hand or point me in the right direction?
    NOTE: in the code pasted above, i am only trying to run one of the four chart demo's listed in the original source in the link.
    NOTE2: in the code pasted above it doesnt show me calling CreateChart() from anywhere, im hoping to get some advice on how to proceed from here.
    Message was edited by:
    amadman

    Here is the netbeans generated code that i had omitted in the post above:
    private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            CreateChart(); //this is one of the many places i tried sticking the function
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 546, Short.MAX_VALUE)
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 398, Short.MAX_VALUE)
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            pack();
        }// </editor-fold>   I believe this is what you mentioned looking for, or close to it:
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);any thoughts?

  • Problem with JPanel

    hello everyone!
    i want to create a GUI consisting of a JTextField and a Jbutton which should be North aligned
    and a JTextArea with a scrollbar south aligned. i created the following code but the button appears cut.
    what's going wrong? could you help me?
    Thanks!
    Here is the code :
          panel=new JPanel();
          panel2=new JPanel();
          enterField = new JTextField(20);
          button=new JButton("Send");
          enterField.setEnabled( false );
          panel.setLayout(new FlowLayout(FlowLayout.LEFT));
          panel.add(enterField);
          panel.add(button);
          displayArea = new JTextArea(10,15);
          displayArea.setEnabled( false );
          scroller = new JScrollPane( displayArea );
          panel2.add(displayArea);
          panel2.add(scroller);
          Container container = getContentPane();
          container.add( panel, BorderLayout.NORTH );
          container.add( panel2, BorderLayout.SOUTH );
          setSize( 300, 150 );
          setVisible( true );

    i changed the code as following but now the label, textfield and the button
    all appear in the same line. But i want they appear the one under the other.
    why does this happen?
          panel=new JPanel();
          panel2=new JPanel();
          label=new JLabel("Choose a number from 1 to 10:");
          enterField = new JTextField(8);
          button=new JButton("Send");
          enterField.setEnabled( false );
          panel.setLayout(new FlowLayout(FlowLayout.CENTER));
          panel.add(label);
          panel.add(enterField);
          panel.add(button);
    displayArea = new JTextArea(5,18);
          displayArea.setEnabled( false );
          scroller = new JScrollPane( displayArea );
          panel2.add(scroller);
          Container container = getContentPane();
          container.add( panel, BorderLayout.NORTH );
          container.add( panel2, BorderLayout.SOUTH );
          //setSize(400,250);
          pack( );
          setVisible( true );

  • How to force to wait and get input from a jframe-jpanel?

    I would like to use a jframe-jpanel to get user input instead of using JOptionPane.showInputDialog since there will be more than 1 input.
    But I could not do it. The code reads the panel lines and passes to other lines below without waiting for the okay button to be pressed.
    This is the part of code of my main frame;
    jLabel10.setText(dene.toString());
    if (dene == 0) {
    // todo add button input panel
    //String todo_write = JOptionPane.showInputDialog("Please enter a todo item");
    JFrame frameTodoAddInput = new JFrame( "Please input..." );
    TodoAddAsk1JPanel todoaddpanel = new TodoAddAsk1JPanel();
    frameTodoAddInput.add(todoaddpanel);
    frameTodoAddInput.setSize( 600, 200 ); // set frame size
    frameTodoAddInput.setLocation(300, 300);
    //String todo_write = todoaddpanel.getNewTodoItem();
    String todo_write = todoaddpanel.getNewTodoItem();
    jLabel10.setText("Satir 1822 de".concat(todo_write));
    // end of todo add button input panel
    todoTextPane1.setText(todo_write);
    This is the code of input panel;
    * TodoAddAsk1JPanel.java
    * Created on May 6, 2007, 12:03 AM
    package javaa;
    public class TodoAddAsk1JPanel extends javax.swing.JPanel {
    /** Creates new form TodoAddAsk1JPanel */
    public TodoAddAsk1JPanel() {
    initComponents();
    private String NewTodoItem = "";
    public String getNewTodoItem() {
    NewTodoItem = ANewTodoItemTextField.getText();
    return this.NewTodoItem;
    /** 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() {
    jLabel1 = new javax.swing.JLabel();
    ANewTodoItemTextField = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    PriorityComboBox = new javax.swing.JComboBox();
    jLabel3 = new javax.swing.JLabel();
    DayValueComboBox = new javax.swing.JComboBox();
    MonthValueComboBox = new javax.swing.JComboBox();
    YearValueComboBox = new javax.swing.JComboBox();
    OkayButton = new javax.swing.JButton();
    CancelButton = new javax.swing.JButton();
    TimeValueComboBox = new javax.swing.JComboBox();
    jLabel1.setText("Please enter a todo item:");
    jLabel2.setText("Please select its priority level:");
    PriorityComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A", "B", "C" }));
    jLabel3.setText("Please select its due date:");
    DayValueComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" }));
    MonthValueComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }));
    YearValueComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030", "2031", "2032", "2033", "2034", "2035", "2036", "2037", "2038", "2039", "2040", "2041", "2042", "2043", "2044", "2045", "2046", "2047", "2048", "2049", "2050", "2051", "2052", "2053", "2054", "2055", "2056", "2057", "2058", "2059", "2060", "2061", "2062", "2063", "2064", "2065", "2066", "2067", "2068", "2069", "2070" }));
    OkayButton.setText("OK");
    OkayButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    OkayButtonActionPerformed(evt);
    CancelButton.setText("Cancel");
    TimeValueComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00", "23:30", "00:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30", "05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00" }));
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE)
    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(PriorityComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(ANewTodoItemTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(OkayButton, javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE)
    .addComponent(CancelButton))
    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
    .addComponent(DayValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(MonthValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
    .addComponent(YearValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addGap(13, 13, 13)
    .addComponent(TimeValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(42, 42, 42)))
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(ANewTodoItemTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel1))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel2)
    .addComponent(PriorityComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel3)
    .addComponent(DayValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(MonthValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(YearValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(TimeValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(18, 18, 18)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(OkayButton)
    .addComponent(CancelButton))
    .addContainerGap())
    }// </editor-fold>
    private void OkayButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    NewTodoItem = ANewTodoItemTextField.getText();
    // Variables declaration - do not modify
    private javax.swing.JTextField ANewTodoItemTextField;
    private javax.swing.JButton CancelButton;
    private javax.swing.JComboBox DayValueComboBox;
    private javax.swing.JComboBox MonthValueComboBox;
    private javax.swing.JButton OkayButton;
    private javax.swing.JComboBox PriorityComboBox;
    private javax.swing.JComboBox TimeValueComboBox;
    private javax.swing.JComboBox YearValueComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration
    I want to get the resulted input of "NewTodoItem"
    Thanks in advance for your kind help.
    Guven

    Thank you very much for your help. But I would like
    to get 3 inputs from 1 window at the same time and I
    could not find any example code for JDialog for more
    than 1 input. If any body can show how to write this
    code, it would be appreciated.
    ThanksYou can write your own. A JDialog is a container just look a JFrame is.

  • Align text in a textarea

    Greetings,
    Could anyone point me out in how to align a text in a textarea?, as in left/right/center ?
    Thank you

    An easy way to do it is to use a JEditorPane... here's an example class:
    package com.clearlyhazy;
    import javax.swing.*;
    import java.awt.*;
    public class AlignableTextPane extends JEditorPane {
         private static String LEFT = "\"LEFT\"";
         private static String CENTER = "\"CENTER\"";
         private static String RIGHT = "\"RIGHT\"";
         private String alignString = LEFT;
         private String realText;
         public AlignableTextPane() {
              super("text/html", "");
         public AlignableTextPane(String align) {
              super("text/html", "");
              setAlignment(align);
         public void setAlignment(String align) {
              if (align.equals(AlignableTextPane.LEFT) || align.equals(AlignableTextPane.CENTER) || align.equals(AlignableTextPane.RIGHT)) {
                   alignString = align;
         public String getText() {
              return realText;
         public void setText(String t) {
              realText = t;
              super.setText("<P ALIGN=" + alignString + ">" + realText + "</P>");
         public void setText(String t, String alignment) {
              alignString = alignment;
              setText(t);
         public static void main(String[] args) {
              JFrame tester = new JFrame("Alignment Test");
              JPanel mainPanel = new JPanel();
              mainPanel.setLayout(new GridLayout(1, 0));
              AlignableTextPane leftPane = new AlignableTextPane(AlignableTextPane.LEFT);
              leftPane.setText("This text is left-aligned.");
              mainPanel.add(leftPane);
              AlignableTextPane centerPane = new AlignableTextPane(AlignableTextPane.CENTER);
              centerPane.setText("This text is center-aligned.");
              mainPanel.add(centerPane);
              AlignableTextPane rightPane = new AlignableTextPane(AlignableTextPane.RIGHT);
              rightPane.setText("This text is right-aligned.");
              mainPanel.add(rightPane);
              tester.setContentPane(mainPanel);
              tester.setSize(400, 400);
              tester.setLocationRelativeTo(null);
              tester.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              tester.setVisible(true);
    }

Maybe you are looking for

  • Streams propagation error

    I have 2 Oracle 11.2 standard edition databases and I am attempting to perform synchronous capture replication from one to the other. I have a propagation rule created with: begin DBMS_STREAMS_ADM.ADD_TABLE_PROPAGATION_RULES( table_name => 'duptest.t

  • Presentation Variable issue in OBIEE 11g

    Hi, I have 2 reports, report 1 and report 2 When i drill down on report 1 column 'Number of id's' will open the details report of Id's report 2 I am using a Presentation variable in report 2 filters (detail report) which is generated in Main report d

  • Problem with full screen flash background

    I want to use a shockwave swf animation as a full screen background for a captivate presentation. If I use, 'rest of movie' to display this swf background, then any objects I try to put on top get covered over by the animation... ie. I can't see them

  • XL Reporter error on report composor - wont launch

    When trying to compose a report get the following error. Unable to create component - Report COmposor.ixreportcomposer class not registered looking ofr object with  CLSID:{35F4532F-F492-47C1-9203-361B0ESA8E22} Anyone got any ideas.

  • Scroll pane issues

    I hope someone can help. I have designed a site and on certain pages there are scroll panes with jpgs. When I preview the movie on my computer everything seems to work fine. When I upload it to the server and look at the page the content that is supp