About setbackground

i wanna know how to fill a text box background
can i do like this:
public void try_this(int i){
if(i==1)
txtbox.setBackground(red);
else
txtbox.setBackground(black);
ehh.... can ah???
Thanks..

The first step (only step?) of a Component is to call Graphics.fillRect() after setting the color to the background color - default color, until you call setBackground(). Each widget derived from Component (just about everything in the AWT) includes a call to super.paint(); to do this. If you write your own paint() method, don't forget this. (Alternative, just do a g.fillRect() after setting whatever color.)

Similar Messages

  • SetBackground(Color c)

    Hello All,
    What do you know about setBackground(Color c) execution ?
    I mean does this function work as PostMessage() or as SendMessage ? Can I be sure that after the funcion has returned this "paint message" has already been processed by the system ?

    Wrong. I suggest you take a look at the code in JComponent:
    public void setBackground(Color bg) {
       Color oldBg = getBackground();
       super.setBackground(bg);
       if ((oldBg != null) ? !oldBg.equals(bg) : ((bg != null) && !bg.equals(oldBg))) {
          // background already bound in AWT1.2
          repaint();
    }But in general if you program in such a way that it matters when exactly
    your component gets repainted, better re-think your approach:
    You should call setBackground() only from AWTs event thread and you
    better don't make long-running calculations in this thread.
    However at the latest your component will get repainted when this
    thread is idle.
    Also, take a look at the JavaDoc of repaint():
    "Adds the specified region to the dirty region list if the component is showing. The component will be repainted after all of the currently pending events have been dispatched."
    So even repaint() does not paint your component immediatly.
    The gist of it: JavaDoc and the JDK sources are your friend.

  • Help Plz! AWT to Swing Conversion

    Hey everyone, I'm new to java and trying to convert this AWT program to Swing, I got no errors, the menu shows but they dont work !! Could somebody please help me? thanks alot!
    Current Under-Construction Code: (no errors)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class zipaint extends JFrame implements ActionListener,      ItemListener,
    MouseListener, MouseMotionListener, WindowListener {
    static final int WIDTH = 800;     // Sketch pad width
    static final int HEIGHT = 600;     // Sketch pad height
    int upperLeftX, upperLeftY;     // Rectangle upper left corner coords.
    int width, height;          // Rectangle size
    int x1, y1, x2, y2, x3, y3, x4, y4; // Point coords.
    boolean fillFlag = false; //default filling option is empty
    boolean eraseFlag = false; //default rubber is off
    String drawColor = new String("black"); //default drawing colour is black
    String drawShape = new String("brush"); //default drawing option is brush
    Image background; //declear image for open option
    private FileDialog selectFile = new FileDialog( this,
    "Select background (.gif .jpg)",
    FileDialog.LOAD );
    // Help
    String helpText = "Draw allows you to sketch different plane shapes over a " +
    "predefined area.\n" + "A shape may be eother filled or in outline, " +
    "and in one of eight different colours.\n\n" + "The position of the " +
    "mouse on the screen is recorded in the bottom left-hand corner of the " +
    "drawing area. The choice of colour and shape are disoplayed also in the " +
    "left-habnd corner of the drawing area.\n\n" + "The size of a shape is " +
    "determined by the mouse being dragged to the final position and " +
    "released. The first click of the mouse will generate a reference dot on " +
    "the screen. This dot will disapear after the mouse button is released.\n\n" +
    "Both the square and the circle only use the distance measured along the " +
    "horizontal axis when determining the size of a shape.\n\n" + "Upon " +
    "selecting erase, press the mouse button, and move the mouse over the " +
    "area to be erased. releasing the mouse button will deactivate erasure.\n\n" +
    "To erase this text area choose clearpad from the TOOLS menu.\n\n";
    // Components
    JTextField color = new JTextField();
    JTextField shape = new JTextField();
    JTextField position = new JTextField();
    CheckboxGroup fillOutline = new CheckboxGroup();
    JTextArea info = new JTextArea(helpText,0,0/*,JTextArea.JSCROLLBARS_VERTICAL_ONLY*/);
    JFrame about = new JFrame("About Zi Paint Shop");
    // Menues
    String[] fileNames = {"Open","Save","Save as","Exit"};
    String[] colorNames = {"black","blue","cyan","gray","green","magenta","red","white","yellow"};
    String[] shapeNames = {"brush","line","square","rectangle","circle","ellipse"};
    String[] toolNames = {"erase","clearpad"};
    String[] helpNames = {"Help","about"};
    public zipaint(String heading) {
    super(heading);
    getContentPane().setBackground(Color.white);
    getContentPane().setLayout(null);
    /* Initialise components */
    initialiseTextFields();
    initializeMenuComponents();
    initializeRadioButtons();
    addWindowListener(this);
    addMouseListener(this);
    addMouseMotionListener(this);
    /* Initialise Text Fields */
    private void initialiseTextFields() {
    // Add text field to show colour of figure
    color.setLocation(5,490);
    color.setSize(80,30);
    color.setBackground(Color.white);
    color.setText(drawColor);
    getContentPane().add(color);
    // Add text field to show shape of figure
    shape.setLocation(5,525);
    shape.setSize(80,30);
    shape.setBackground(Color.white);
    shape.setText(drawShape);
    getContentPane().add(shape);
    // Add text field to show position of mouse
    position.setLocation(5,560);
    position.setSize(80,30);
    position.setBackground(Color.white);
    getContentPane().add(position);
    // Set up text field for help
    info.setLocation(150,250);
    info.setSize(500,100);
    info.setBackground(Color.white);
    info.setEditable(false);
    private void initializeMenuComponents() {
    // Create menu bar
    JMenuBar bar = new JMenuBar();
    // Add colurs menu
    JMenu files = new JMenu("Files");
    for(int index=0;index < fileNames.length;index++)
    files.add(fileNames[index]);
    bar.add(files);
    files.addActionListener(this);
    // Add colurs menu
    JMenu colors = new JMenu("COLORS");
    for(int index=0;index < colorNames.length;index++)
    colors.add(colorNames[index]);
    bar.add(colors);
    colors.addActionListener(this);
    // Add shapes menu
    JMenu shapes = new JMenu("SHAPES");
    for(int index=0;index < shapeNames.length;index++)
    shapes.add(shapeNames[index]);
    bar.add(shapes);
    shapes.addActionListener(this);
    // Add tools menu
    JMenu tools = new JMenu("TOOLS");
    for(int index=0;index < toolNames.length;index++)
    tools.add(toolNames[index]);
    bar.add(tools);
    tools.addActionListener(this);
    // Add help menu
    JMenu help = new JMenu("HELP");
    for(int index=0;index < helpNames.length;index++)
    help.add(helpNames[index]);
    bar.add(help);
    help.addActionListener(this);
    // Set up menu bar
    setJMenuBar(bar);
    /* Initilalise Radio Buttons */
    private void initializeRadioButtons() {
    // Define checkbox
    Checkbox fill = new Checkbox("fill",fillOutline,false);
    Checkbox outline = new Checkbox("outline",fillOutline,true);
    // Fill buttom
    fill.setLocation(5,455);
    fill.setSize(80,30);
    getContentPane().add(fill);
    fill.addItemListener(this);
    // Outline button
    outline.setLocation(5,420);
    outline.setSize(80,30);
    getContentPane().add(outline);
    outline.addItemListener(this);
    /* Action performed. Detects which item has been selected from a menu */
    public void actionPerformed(ActionEvent e) {
    Graphics g = getGraphics();
    String source = e.getActionCommand();
    // Identify chosen colour if any
    for (int index=0;index < colorNames.length;index++) {
    if (source.equals(colorNames[index])) {
    drawColor = colorNames[index];
    color.setText(drawColor);
    return;
    // Identify chosen shape if any
    for (int index=0;index < shapeNames.length;index++) {
    if (source.equals(shapeNames[index])) {
    drawShape = shapeNames[index];
    shape.setText(drawShape);
    return;
    // Identify chosen tools if any
    if (source.equals("erase")) {
    eraseFlag= true;
    return;
    else {
    if (source.equals("clearpad")) {
    remove(info);
    g.clearRect(0,0,800,600);
    return;
    if (source.equals("Open")) {
    selectFile.setVisible( true );
    if( selectFile.getFile() != null )
    String fileLocation = selectFile.getDirectory() + selectFile.getFile();
    background = Toolkit.getDefaultToolkit().getImage(fileLocation);
    paint(getGraphics());
    if (source.equals("Exit")) {
    System.exit( 0 );
    // Identify chosen help
    if (source.equals("Help")) {
    getContentPane().add(info);
    return;
    if (source.equals("about")) {
    displayAboutWindow(about);
    return;
    public void paint(Graphics g)
    super.paint(g);
    if(background != null)
    Graphics gc = getGraphics();
    gc.drawImage( background, 0, 0, this.getWidth(), this.getHeight(), this);
    /* Dispaly About Window: Shows iformation aboutb Draw programme in
    separate window */
    private void displayAboutWindow(JFrame about) {
    about.setLocation(300,300);
    about.setSize(350,160);
    about.setBackground(Color.cyan);
    about.setFont(new Font("Serif",Font.ITALIC,14));
    about.setLayout(new FlowLayout(FlowLayout.LEFT));
    about.add(new Label("Author: Zi Feng Yao"));
    about.add(new Label("Title: Zi Paint Shop"));
    about.add(new Label("Version: 1.0"));
    about.setVisible(true);
    about.addWindowListener(this);
    // ----------------------- ITEM LISTENERS -------------------
    /* Item state changed: detect radio button presses. */
    public void itemStateChanged(ItemEvent event) {
    if (event.getItem() == "fill") fillFlag=true;
    else if (event.getItem() == "outline") fillFlag=false;
    // ---------------------- MOUSE LISTENERS -------------------
    /* Blank mouse listener methods */
    public void mouseClicked(MouseEvent event) {}
    public void mouseEntered(MouseEvent event) {}
    public void mouseExited(MouseEvent event) {}
    /* Mouse pressed: Get start coordinates */
    public void mousePressed(MouseEvent event) {
    // Cannot draw if erase flag switched on.
    if (eraseFlag) return;
    // Else set parameters to 0 and proceed
    upperLeftX=0;
    upperLeftY=0;
    width=0;
    height=0;
    x1=event.getX();
    y1=event.getY();
    x3=event.getX();
    y3=event.getY();
    Graphics g = getGraphics();
    displayMouseCoordinates(x1,y1);
    public void mouseReleased(MouseEvent event) {
    Graphics g = getGraphics();
    // Get and display mouse coordinates
    x2=event.getX();
    y2=event.getY();
    displayMouseCoordinates(x2,y2);
    // If erase flag set to true reset to false
    if (eraseFlag) {
    eraseFlag = false;
    return;
    // Else draw shape
    selectColor(g);
    if (drawShape.equals("line")) g.drawLine(x1,y1,x2,y2);
    else if (drawShape.equals("brush"));
    else drawClosedShape(drawShape,g);
    /* Display Mouse Coordinates */
    private void displayMouseCoordinates(int x, int y) {
    position.setText("[" + String.valueOf(x) + "," + String.valueOf(y) + "]");
    /* Select colour */
    private void selectColor(Graphics g) {
    for (int index=0;index < colorNames.length;index++) {
    if (drawColor.equals(colorNames[index])) {
    switch(index) {
    case 0: g.setColor(Color.black);break;
    case 1: g.setColor(Color.blue);break;
    case 2: g.setColor(Color.cyan);break;
    case 3: g.setColor(Color.gray);break;
    case 4: g.setColor(Color.green);break;
    case 5: g.setColor(Color.magenta);break;
    case 6: g.setColor(Color.red);break;
    case 7: g.setColor(Color.white);break;
    default: g.setColor(Color.yellow);
    /* Draw closed shape */
    private void drawClosedShape(String shape,Graphics g) {
    // Calculate correct parameters for shape
    upperLeftX = Math.min(x1,x2);
    upperLeftY = Math.min(y1,y2);
    width = Math.abs(x1-x2);
    height = Math.abs(y1-y2);
    // Draw appropriate shape
    if (shape.equals("square")) {
    if (fillFlag) g.fillRect(upperLeftX,upperLeftY,width,width);
    else g.drawRect(upperLeftX,upperLeftY,width,width);
    else {
    if (shape.equals("rectangle")) {
    if (fillFlag) g.fillRect(upperLeftX,upperLeftY,width,height);
    else g.drawRect(upperLeftX,upperLeftY,width,height);
    else {
    if (shape.equals("circle")) {
    if (fillFlag) g.fillOval(upperLeftX,upperLeftY,width,width);
    else g.drawOval(upperLeftX,upperLeftY,width,width);
    else {
    if (fillFlag) g.fillOval(upperLeftX,upperLeftY,width,height);
    else g.drawOval(upperLeftX,upperLeftY,width,height);
    /* Mouse moved */
    public void mouseMoved(MouseEvent event) {
    displayMouseCoordinates(event.getX(),event.getY());
    /* Mouse dragged */
    public void mouseDragged(MouseEvent event) {
    Graphics g = getGraphics();
    x2=event.getX();
    y2=event.getY();
    x4=event.getX();
    y4=event.getY();
    displayMouseCoordinates(x1,y1);
    if (eraseFlag) g.clearRect(x2,y2,10,10);
    else {
    selectColor(g);
    if(drawShape.equals("brush")) g.drawLine(x3,y3,x4,y4);
    x3 = x4;
    y3 = y4;
    // ---------------------- WINDOW LISTENERS -------------------
    /* Blank methods for window listener */
    public void windowClosed(WindowEvent event) {}
    public void windowDeiconified(WindowEvent event) {}
    public void windowIconified(WindowEvent event) {}
    public void windowActivated(WindowEvent event) {}
    public void windowDeactivated(WindowEvent event) {}
    public void windowOpened(WindowEvent event) {}
    /* Window Closing */
    public void windowClosing(WindowEvent event) {
    if (event.getWindow() == about) {
    about.dispose();
    return;
    else System.exit(0);
    Code End
    Thanks again!
    class ziapp {
    /* Main method */
    public static void main(String[] args) {
    zipaint screen = new zipaint("Zi Paint Shop");
    screen.setSize(zipaint.WIDTH,zipaint.HEIGHT);
    screen.setVisible(true);

    First of all use the [url http://forum.java.sun.com/features.jsp#Formatting]Formatting Tags when posting code to the forum. I'm sure you don't code with every line left justified so we don't want to read unformatted code either.
    Hey everyone, I'm new to java and trying to convert this AWT program to SwingInstead of converting the whole program, start with something small, understand how it works and then convert a different part of the program. You can start by reading this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]How to Use Menus.
    From a quick glance of your code it looks like you are not adding an ActionListener to your JMenuItems. You are adding them to the JMenu.
    Other observations:
    1) Don't mix AWT with Swing components. You are still using CheckBox
    2) Don't override paint(). When using Swing you should override paintComponent();
    3) Use LayoutManagers. Using a null layout does not allow for easy maintenance of the gui. Right now you are using 800 x 600 as your screen size. Most people are probably using at least 1024 x 768 screen sizes. When using LayoutManagers you would suggest component sizes by using setPreferredSize(), not setSize().

  • Can You Help Me ABout getSelectedRow in JTable

    Can you help me on how to solve my problem about the getSelectedRow .....
    I have one JComboBox and a SearchButton
    ... Once I selected an Item in a JComboBox, I will press the SearchButton
    and then it will look up to the database and display it in the JTable..........
    i used the getSelectedRow to print the value that I selected in the table...
    like this...
    public void mouseClicked(MouseEvent e) {
    // Ilabas yung form
    if(e.getClickCount() == 1 ) {
    System.out.println(table1.getSelectedRow());
    In the first press in the SearchButton and then clicking the row
    , It will print the selected row...... but when i press again the SearchButton then clicking a row again........
    there is a problem occured....... selectedRow is always -1, can you help me to solve this.....

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.plaf.metal.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.text.*;
    import java.beans.*;
    public class OpenProject extends JDialog {
         ResultSet rs, rs1, rs2, rs3;
         JFrame JFParentFrame; // create a JFrame
         JFrame OwnerFrame; // create a JFrame
         public JLabel proj_name;
         public JLabel proj = new JLabel("Project Name:");
         public JLabel form = new JLabel("Form Name");
         public JLabel lang = new JLabel("Language");
         public JComboBox form_lang = new JComboBox();
         public JComboBox form_name = new JComboBox();
         public JButton edit = new JButton("Edit");
         public JButton reload = new JButton("Search");
         public JButton def = new JButton("Set Text Default");
         public JButton langs = new JButton("Add Language");
         public JButton exit = new JButton("Exit");
         public JPanel panel1 = new JPanel ();
         public JTable table1, table2, table3,table4;
         public JScrollPane scrollPane1, scrollPane2, scrollPane3, scrollPane4;
         public JTabbedPane UITab,UITab1;
         Container c = getContentPane();
         Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
         public String column[][];
         public String strRow;
         public String strCol;
         public String strForm;
         public String strGetProj_id;
         public String strForm_lang;
         public String strForm_name;
         private boolean DEBUG = false;
         public int getLang;
         public int getForm;
         public int getDef_id;
         public int count2 = 0,count3 = 0,count4 = 0;
         public int row2 = 0,row3 = 0,row4 = 0;
         public int selectedRow1 = 0, selectedRow2 = 0;
         public DbBean db = new DbBean();
         public OpenProject(JFrame OwnerForm, String getProj_id) {
              super(OwnerForm,true);
                   strGetProj_id = getProj_id;
              try{
                   db.connect();
              } catch(SQLException sqlex) {
              } catch(ClassNotFoundException cnfex) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch(Exception e) {
              // Para ito sa paglalagay sa dalawang combo box ng value.......
              try {
                   rs = db.execSQL("Select * from mst_form where form_proj_id = "+strGetProj_id+"");
                   while(rs.next()) {
                        form_name.addItem(rs.getString("form_name"));
                        //System.out.println(strForm);
              } catch(SQLException sqlex) {
              try {
                   rs = db.execSQL("Select distinct from mst_form where form_proj_id = "+strGetProj_id+"");
                   while(rs.next()) {
                        form_name.addItem(rs.getString("form_name"));
                        //System.out.println(strForm);
              } catch(SQLException sqlex) {
              try {
                   int counts;
                   rs = db.execSQL("Select * from mst_project where proj_id = "+strGetProj_id+"");
                   while(rs.next()) {
                        counts = rs.getInt("proj_lang_id");
                        System.out.println(counts);
                        rs1 = db.execSQL("Select * from mst_language where lang_id = "+counts+"");
                        while (rs1.next()) {
                             form_lang.addItem(rs1.getString("lang_name"));     
              } catch(SQLException sqlex) {
              edit.setActionCommand("edit");
              edit.addActionListener(actions);
              reload.setActionCommand("load");
              reload.addActionListener(actions);
              def.setActionCommand("default");
              def.addActionListener(actions);
              langs.setActionCommand("lang");
              langs.addActionListener(actions);
              exit.setActionCommand("exit");
              exit.addActionListener(actions);
              proj_name = new JLabel();     
              proj_name.setBackground(new Color(255,255,255));
              form_name.setMaximumRowCount(5);
              form_name.setBackground(new Color(255,255,255));
              form_lang.setMaximumRowCount(5);
              form_lang.setBackground(new Color(255,255,255));
              proj.setBounds(20, 20,100,20);
              proj_name.setBounds(120, 20,250,20);
              form.setBounds(20, 50,100,20);
              form_name.setBounds(120, 50,150,20);
              lang.setBounds(300, 50,100,20);     
              form_lang.setBounds(380, 50,150,20);
              reload.setBounds(560,50,80, 20);
              edit.setBounds(110,360,115,20);
              def.setBounds(230,360,115,20);
              langs.setBounds(350,360,115,20);
              exit.setBounds(470,360,115,20);
              panel1.add(getTable());
              panel1.setLayout(null);     
              panel1.setBackground(Color.white);     
              panel1.add(proj);
              panel1.add(proj_name);
              panel1.add(form);
              panel1.add(form_name);
              panel1.add(lang);
              panel1.add(form_lang);
              panel1.add(reload);     
              panel1.add(def);
              panel1.add(langs);
              panel1.add(exit);
              panel1.add(edit);
              c.add(panel1);
              setSize(680,420);
              setTitle("Open Project");
              setLocation((screen.width - 590)/2,((screen.height - 280)/2) - 45);
         public JTabbedPane getTable() {
              UITab = new JTabbedPane();
              strForm_lang = form_lang.getSelectedItem().toString();
              strForm_name = form_name.getSelectedItem().toString();
              int count1=0;
              int row1=0;
              try {
                   rs = db.execSQL("Select * from mst_default where def_proj_id = '"+strGetProj_id+"' AND def_category = 'Title'" );
                   while(rs.next()) {
                        count1 += 1;
                        getDef_id = rs.getInt("def_id");
                   column = new String[count1][2];
                   rs1 = db.execSQL("Select form_id from mst_form WHERE form_name = '"+strForm_name+"'");
                   while(rs1.next()) {
                        getForm = rs1.getInt("form_id");
                        System.out.println("getForm");
                   rs2 = db.execSQL("Select lang_id from mst_language WHERE lang_name = '"+strForm_lang+"'");
                   while(rs2.next()) {
                        getLang = rs2.getInt("lang_id");
                        System.out.println("getLang");
                   rs3 = db.execSQL("Select * from mst_default a, mst_translation b WHERE a.def_form_id = '"+getForm+"' AND b.trans_lang_id = '"+getLang+"' AND a.def_proj_id = '"+strGetProj_id+"' AND b.trans_def_id = '"+getDef_id+"' AND a.def_category = 'Title' " );
                   while(rs3.next()) {
                        column[row1][0] = "" + rs3.getString("display_name");          // rowNum ay kung ilan ang row na ilalabas
                   column[row1][1] = "" + rs3.getString("translation"); // Default yung isang array ng column ko, kaya fixed
                        row1++;
                   row1 = 0;
              } catch(SQLException sqlex) {
                   sqlex.printStackTrace();
                   System.exit(1);
              // End
              table1 = new JTable(new MyTableModel()){
              scrollPane1 = new JScrollPane(table1);
              UITab.setBounds(30,100,610,250);
              UITab.add("Title",scrollPane1);
              return UITab;
         class MyTableModel extends AbstractTableModel {     
                   // Pagawa ng header Coloumn
                   String ColumnHeaderName[] = {
                        "Default Text",""+strForm_lang+" Translation"
                   //End
                   public int getColumnCount() {     
                        //System.out.println("The Column Count is" + ColumnHeaderName.length);
         return ColumnHeaderName.length;
         public int getRowCount() {
              //System.out.println("The Row Count is" + column.length);
         return column.length;
         public String getColumnName(int col) {
                        //System.out.println("The Column Name is" + ColumnHeaderName[col]);     
         return ColumnHeaderName[col];
         public Object getValueAt(int row,int col) {
              System.out.println("The value at row and column = " + column[row][col]);
         return column[row][col];
         public int getSelectedRow() {
              System.out.println("Integer" + column.length);
              return column.length;
         ActionListener actions = new ActionListener() {
              public void actionPerformed(ActionEvent ae) {
                   String source = ae.getActionCommand();
                   if (source == "load") {
                        table1.clearSelection();
                        panel1.add(getTable());
                        table1.addNotify();
                        repaint();
                   } else if (source == "default") {
                        dispose();
                        TextDefaultForm form = new TextDefaultForm(OwnerFrame,JFParentFrame);
                        form.setVisible(true);
                   } else if (source == "lang") {
                        dispose();
                        CreateProject lang = new CreateProject(JFParentFrame);
                        lang.setVisible(true);
                   } else if (source == "exit") {
                        dispose();
                   } else if (source == "edit") {
                        if (table1.getValueAt(table1.getSelectedRow(),table1.getSelectedColumn()) != null){
                             formLang lang = new formLang(OwnerFrame,strCol,strRow, strGetProj_id);
                             lang.setVisible(true);
         MouseListener MouseTableListener = new MouseListener() {
                   public void mouseClicked(MouseEvent e) {
                        // Ilabas yung form
                        if(e.getClickCount() == 2 ) {
                             dispose();
                             int col_a = 0;
                             int col_b = 1;
                             selectedRow1 = table1.getSelectedRow();     
                             Object objColumn1 = table1.getValueAt(selectedRow1, col_a);
                             Object objRow1 = table1.getValueAt(selectedRow1, col_b);
                             strCol = objColumn1.toString();
                             strRow = objRow1.toString();
                             formLang lang = new formLang(OwnerFrame,strCol,strRow,strGetProj_id);
                             System.out.println(selectedRow1);
                             System.out.println(strCol);
                             System.out.println(strRow);
                             lang.txtProj.setText(strCol);
                             lang.txtLang.setText(strRow);
                             lang.show();
                        } else if (e.getClickCount() == 1) {
                             table1.setSelectionBackground(Color.blue);
                             table1.setColumnSelectionAllowed(false);
                        table1.setRowSelectionAllowed(true);
                        table1.setFocusable(true);
                             int a = table1.getRowCount();
                             System.out.println("Row Count = " + a);
                             int sel = table1.getSelectedRow();     
                             //if (sel == -1) return;
                             System.out.println("Selected Row = " + sel);
                             System.out.println(table1.isRowSelected(sel));
                   public void mouseReleased(MouseEvent e) {
                   public void mouseExited(MouseEvent e) {
                   public void mouseEntered(MouseEvent e) {
                   public void mousePressed(MouseEvent e) {
         //public static void main(String leo[]) {
              //OpenProject open = new OpenProject();
    }

  • JButton.setBackground(Color color) not working

    With JDK 1.4.2, my JButtons below have a blue background. When I compile with 1.5, they are gray. I tried using setOpaque(true) on one of them below. It didn't work. Any ideas?
    class MainMenu extends JFrame
        public MainMenu() throws Exception
            super("");// no title on main menu
            JPanel pane = new JPanel(null, true);
            pane.setBackground(new Color(4194496));
            Icon icon = new ImageIcon(BizThriveMenu.getResourceDir()+"\\BizThriveSmall.gif");
            JLabel lImage = new JLabel(icon);
            JButton bEditCustomers = new JButton("<html><FONT COLOR=WHITE>Customers</FONT></html>");
            bEditCustomers.setOpaque(true);
            bEditCustomers.setBackground(new Color(4194496));
            JButton bAccounting = new JButton("<html><FONT COLOR=WHITE>Accounting</FONT></html>");
            bAccounting.setBackground(new Color(4194496));
            JButton bEditReminders = new JButton("<html><FONT COLOR=WHITE>Reminders</FONT></html>");
            bEditReminders.setBackground(new Color(4194496));
            JButton bPublish = new JButton("<html><FONT COLOR=WHITE>Publish</FONT></html>");
            bPublish.setBackground(new Color(4194496));
            JButton bExit = new JButton("<html><FONT COLOR=WHITE>Exit</FONT></html>");
            bExit.setBackground(new Color(4194496));
            bEditCustomers.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent actionEvent) {
                        try {
                            new TableListFrame(MainMenu.this, "customers");
                        catch (Exception e) {
                            e.printStackTrace();
            bAccounting.addActionListener(
                    new ActionListener() {
                        public void actionPerformed(ActionEvent actionEvent) {
                            try {
                                new AccountCategoryListFrame(MainMenu.this, "accountCategories");
                            catch (Exception e) {
                                e.printStackTrace();
            bEditReminders.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent actionEvent) {
                        try {
                            new CurrentRemindersFrame(MainMenu.this);
                        catch (Exception e) {
                            e.printStackTrace();
            bPublish.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent actionEvent) {
                        try {
                            new Designer(MainMenu.this);
                        catch (Exception e) {
                            e.printStackTrace();
            bExit.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent actionEvent) {
                        System.exit(0);
            Font buttonFont = bEditCustomers.getFont();
            buttonFont = new Font("Times New Roman", Font.ITALIC+Font.BOLD, 24);
            bEditCustomers.setFont(buttonFont);
            bAccounting.setFont(buttonFont);
            bEditReminders.setFont(buttonFont);
            bPublish.setFont(buttonFont);
            bExit.setFont(buttonFont);
            pane.add(lImage);
            pane.add(bEditCustomers);
            pane.add(bAccounting);
            pane.add(bEditReminders);
            pane.add(bPublish);
            pane.add(bExit);
            int appWidth = 500;
            int appHeight = 700;
            this.setSize(new Dimension(appWidth,appHeight));
            this.setResizable(false);
            this.getContentPane().add(pane);
            Insets insets = pane.getInsets();
            lImage.setBounds(((appWidth-4-icon.getIconWidth())/2)+insets.left, 35+insets.top, icon.getIconWidth(), icon.getIconHeight());
            bEditCustomers.setBounds(((appWidth-4-235)/2)+insets.left,  200 + insets.top, 235, 40);
            bAccounting.setBounds(((appWidth-4-235)/2)+insets.left,  250 + insets.top, 235, 40);
            bEditReminders.setBounds(((appWidth-4-235)/2)+insets.left,  300 + insets.top, 235, 40);
            bPublish.setBounds(((appWidth-4-235)/2)+insets.left,  350 + insets.top, 235, 40);
            bExit.setBounds(((appWidth-4-235)/2)+insets.left,  400 + insets.top, 235, 40);
            //center application window on desktop
            Dimension screenSize = null;;
            screenSize = getToolkit().getScreenSize();
            this.setBounds((screenSize.width - appWidth)/2,
                (screenSize.height - appHeight)/2, appWidth, appHeight);
            // make the frame visible
            this.setVisible(true);
        }

    As a newbie to the forum you obviously didn't understand how to post a simple direct question, with only the relevant code to demonstrate the problem, which is why I provided you with all the extra information to help you get better answers in the future.
    Did you bother to read the link of creating an SSCCE?
    Your question is about setting the background color of a button. 99% of the code you posted is not related to that issue. Keep the code simple so we don't waste time reading through unnecessary code. That way we can determine whether the problem is with your code or the environment as I already mentioned.
    1) Though the information about setting the text color is helpful, the
    background color of the button is the subject of the posting. Please
    limit your replies to the subject of the posting.If the code posted was only related to the background color then we wouldn't have this issue now would we? When I see something strange or wrong I make a comment whether it is directly related to the question or not. It has been my experience that most people appreciate the bonus advice, so I will not change my behaviour for you. If you don't like the advice, then just ignore it.
    2) Regarding, "I don't use 1.5 so I can't really help you, but neither can
    anybody else...", please read Michael_Dunn's post, who remarkably
    was able to provide help.My comment was related to the code you provided. Nobody could use the code to compile and execute to see if it ran on their machine. So, Michael, had to waste time creating his own simple test program to see if it worked, which it did.
    My point was if you provided the same simple demo program that Michael did, then all he (or anybody else) would have had to do would be to copy, compile and test the program. You should be spending the time creating the simple test program not each of us individually. Think of how much time is wasted if everybody who wanted to help you had to create their own program? Thats why I included the link on creating an SSCCE, so the next time we don't need to waste time.
    3) ..... Otherwise, it's alright not to reply to a subject. Nobody will think less of you.Of course I don't have to replay to every question (and I don't), but if you don't learn to post a question properly you will make the same mistake again and again. That was the context of my answer. It was designed to help you ask a better question the next time.
    4) Your comment, "And don't forget to use the Code Formatting Tags > so the code retains its original formatting." That was a standard message I use for many newbies to the forum. I'm amazed at the number of people who think we are mind readers and can guess exactly what is causing the problem without posting any code. So I got tired of typing in a different message every time and I now just cut and paste. Yes I could have edited the last line out, but you would be amazed at how many people format the code the first time but then forget to do it when prompted for more detail. So I just keep it in all messages.
    Please keep your comments related to the problem. I think I've learned a think or two over the years on how to ask and answer a question.

  • SetBackground() Is Not Working in Windows 7

    It looks like inheritance is broken in the component hierarchy for JFrame in Windows 7 JDK 1.6.0_23-b05. Run this code to reproduce the issue.
    public class Main
    public static void main(String[] args)
    JFrame frame = new JFrame();
    frame.setTitle("Test Background");
    frame.setLocation(200, 100);
    frame.setSize(600,400);
    frame.addWindowListener(new WindowAdapter()
    @Override public void windowClosing(WindowEvent e) { System.exit(0); }
    JPanel southPanel = new JPanel();
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(southPanel, BorderLayout.CENTER);
    frame.getContentPane().add(Box.createVerticalStrut(50), BorderLayout.NORTH);
    frame.getContentPane().add(Box.createVerticalStrut(50), BorderLayout.SOUTH);
    frame.getContentPane().add(Box.createHorizontalStrut(50), BorderLayout.WEST);
    frame.getContentPane().add(Box.createHorizontalStrut(50), BorderLayout.EAST);
    southPanel.setBorder(new LineBorder(Color.BLACK));
    frame.getContentPane().setBackground(Color.BLUE);
    frame.setVisible(true);
    }

    user13509659 wrote:
    Run this code to reproduce the issue.Which issue?
    It looks like inheritance is broken in the component hierarchy for JFrame in Windows 7 JDK 1.6.0_23-b05. The only thing remotely related to inheritance in your code snippet is the WindowListener, which does little. See camickr's advice about built-in exit management.
    EDIT - using the post title as a clue, I realize you may be talking about the component hierarchy, and whether the contentPane's background is visible through the upper layers. Instead of guessing, I'd prefer you describe your "issue" accurately (observed vs expected behavior).
    Edited by: jduprez on Feb 10, 2011 1:01 PM

  • Please, help a newbie:  Question about animating expanding containers

    Hi All,
    Short Version of my Question:
    I'm making a media player that needs to have an animation for panels sliding up and down and left and right, and the method I've been using to do this performs far slower than the speed I believe is possible, and required. What is a fast way to make a high performance animation for such an application?
    Details:
    So far, to do the animation, I've been using JSplitPanes and changing the position of the divider in a loop and calling paintImmediately or paintDirtyRegion like so:
    public void animateDividerLocation( JSplitPane j, int to, int direction) {
    for(int i=j.getDividerLocation(); i>=to; i-=JUMP_SIZE) {
    j.setDividerLocation(i);
    j.validate();
    j.paintImmediately(0, 0, j.getWidth(), j.getHeight());
    The validate and paintImmediately calls have been necessary to see any changes while the loop is going. I.e., if those calls are left out, the components appear to just skip right to where they were supposed to animate to, without having been animated at all.
    The animation requirement is pretty simple. Basically, the application looks like it has 3 panels. One on the right, one on the left, and a toolbar at the bottom. The animation just needs to make the panels expand and contract.
    Currenly, the animation only gets about, say, 4 frames a second on the 800 MHz Transmeta Crusoe processor, 114 MB Ram, Windows 2000 machine I must use (to approximate the performance of the processor I'll be using, which will run embedded Linux), even though I've taken most of the visible components out of the JPanels during the animation. I don't think this has to do with RAM reaching capacity, as the harddrive light does not light up often. Even if this were the case, the animation goes also goes slow (about 13 frames a second) on my 3 GHz P4 Windows XP if I keeps some JButtons, images etc., inside the JPanels. I get about 50 frames/sec on my 3 GHz P4, if I take most of the JButtons out, as I do for the 800 MHz processor. This is sufficient to animate the panels 400 pixels across the screen at 20 pixels per jump, but it isn't fast or smooth enough to animate across 400 pixels moving at 4 pixel jumps. I know 50 frames/sec is generally considered fast, but in this case, there is hardly anything changing on the screen (hardly any dirty pixels per new frame) and so I'd expect there to be some way to make the animation go much faster and smoother, since I've seen games and other application do much more much faster and much smoother.
    I'm hoping someone can suggest a different, faster way to do the animation I require. Perhaps using the JSplitPane trick is not a good idea in terms of performance. Perhaps there are some tricks I can apply to my JSplitPane trick?
    I haven't been using any fancy tricks - no double buffering, volatile images, canvas or other animation speed techniques. I haven't ever used any of those things as I'm fairly new to Swing and the 2D API. Actually I've read somewhere that Swing does double buffering without being told to, if I understood what I read. Is doing double buffering explicitly still required? And, if I do need to use double buffering or canvas or volatile images or anything else, I'm not sure how I would apply those techiniques to my problem, since I'm not animating a static image around the screen, but rather a set of containers (JSplitPanes and JPanels, mostly) and components (mostly JButtons) that often get re-adjusted or expanded as they are being animated. Do I need to get the Graphics object of the top container (would that contain the graphics objects for all the contained components?) and then double buffer, volatile image it, do the animation on a canvas, or something like that? Or what?
    Thanks you SO much for any help!
    Cortar
    Related Issues(?) (Secondary concerns):
    Although there are only three main panels, the actual number of GUI components I'm using, during the time of animation, is about 20 JPanels/JSplitPanes and 10 JButtons. Among the JPanels and the JSplitPanes, only a few JPanels are set to visible. I, for one, don't think this higher number of components is what is slowing me down, as I've tried taking out some components on my 3GHz machine and it didn't seem to affect performance much, if any. Am I wrong? Will minimizing components be among the necessary steps towards better performance?
    Anyhow, the total number of JContainers that the application creates (mostly JPanels) is perhaps less than 100, and the total number of JComponents created (mostly JButtons and ImageIcons) is less than 200. The application somehow manages to use up 50 MBs RAM. Why? Without looking at the code, can anyone offer a FAQ type of answer to this?

    You can comment out the lines that add buttons to the panels to see the behavior with empty panels.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.Timer;
    public class DancingPanels
        static GridBagLayout gridbag = new GridBagLayout();
        static Timer timer;
        static int delay = 40;
        static int weightInc = 50;
        static boolean goLeft = false;
        public static void main(String[] args)
            final GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            gbc.fill = gbc.HORIZONTAL;
            final JPanel leftPanel = new JPanel(gridbag);
            leftPanel.setBackground(Color.blue);
            gbc.insets = new Insets(0,30,0,30);
            leftPanel.add(new JButton("1"), gbc);
            leftPanel.add(new JButton("2"), gbc);
            final JPanel rightPanel = new JPanel(gridbag);
            rightPanel.setBackground(Color.yellow);
            gbc.insets = new Insets(30,50,30,50);
            gbc.gridwidth = gbc.REMAINDER;
            rightPanel.add(new JButton("3"), gbc);
            rightPanel.add(new JButton("4"), gbc);
            final JPanel panel = new JPanel(gridbag);
            gbc.fill = gbc.BOTH;
            gbc.insets = new Insets(0,0,0,0);
            gbc.gridwidth = gbc.RELATIVE;
            panel.add(leftPanel, gbc);
            gbc.gridwidth = gbc.REMAINDER;
            panel.add(rightPanel, gbc);
            timer = new Timer(delay, new ActionListener()
                    gbc.fill = gbc.BOTH;
                    gbc.gridwidth = 1;
                public void actionPerformed(ActionEvent e)
                    double[] w = cycleWeights();
                    gbc.weightx = w[0];
                    gridbag.setConstraints(leftPanel, gbc);
                    gbc.weightx = w[1];
                    gridbag.setConstraints(rightPanel, gbc);
                    panel.revalidate();
                    panel.repaint();
            JFrame f = new JFrame("Dancing Panels");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(panel);
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
            timer.start();
        private static double[] cycleWeights()
            if(goLeft)
                weightInc--;
            else
                weightInc++;
            if(weightInc > 100)
                weightInc = 100;
                goLeft = true;
            if(weightInc < 0)
                weightInc = 0;
                goLeft = false;
            double wLeft = weightInc/ 100.0;
            double wRight = (100 - weightInc)/100.0;
            return new double[]{wLeft, wRight};
    }

  • Quick Q about Jtree

    Hey, here is the scenario...a Jtree is in JScrollPane.. i can set tree background by calling myTree.setBackground(), and I can set the text color of tree node by creating my own JTreeCellRenderer to override the getTreeCellRender() .. but there is always a shadow around the tree bnode. I tried JComponent)mytree.getTreeCellRender().setOpaque(false) , then set treeCellRender.background..but it doesnot work.. any insight?

    sorry about my Typo. Tree bnode = Tree Node. Every node (including root ) has an urgly shadow!!

  • SetBackground() useless for JComponent?

    if you extend JComponent and then use setBackground(Color.RED), actually there is no change of the background.
    According to the API doc,
    public void setBackground(Color bg)
    Sets the background color of this component. The background color is used only if the component is opaque, and only by subclasses of JComponent or ComponentUI implementations. Direct subclasses of JComponent must override paintComponent to honor this property.
    It is up to the look and feel to honor this property, some may choose to ignore it.
    even if I set the JComponent to be opaque or override paintComponent() method, it doesn't work.
    codes are as follow:
    class MyComponent extends JComponent
    {   public void paintComponent(Graphics g)
        {    setOpaque(true);
             setBackground(Color.RED);  // no use :(
    }so how to interpretate that method detail of api doc? and how to use setBackgound() method to set the background color of a JComponent.
    BTW, if i extend JPanel instead, then in the paintComponent() method, I have to call super.paintComponent(g) --> why so?
    thx in advance

    so if i want to fill the background with RED (it already has some shapes painted on it)I suggest you read about Swing's painting architecture, as described in the tutorial .
    When paintComponent() is invoked (by the Swing painting framework) it is supposed to paint everything (background +++ "other shapes") in the painting rectangle, except:
    - the components underneath (which may appear if your own component is translucent, but that's a bit involved), including the immediate parent Container and its parent container hierarchy, which have automatically paint themselves in that area when their own paintComponent method, before your paintComponent() method was called in turn
    - the components above, which will automatically paint themselves over what your paintComponent() method is just painting, when their own paintComponent method is called in turn.
    If your JComponent subclass paints two things (say, a background fill, and green squares on top of that), it has to paint both each time your paintComponent is called, on the supllied Graphics rectangle.
    class MyComponent extends JComponent
    {   public MyComponent()
        {    setBackground(Color.RED);
        public void paintComponent(Graphics g)
        {    Graphics2D g2=(Graphics2D)g;
             g2.fill(...); // rectangle of background color
             g2.draw(...); // whatever is supposed to appear on top
    if it is g2.fillRect(0,0,getWidth(),getHeight()), then it will cover other drawings on the component.Maybe, but you will redraw those drawings just after filling the rectangle, so they will appear anyway.
    Now if you're concerned with doing an animation, there are a lot of techniques to optimize painting so as to not repaint everything, but do some practice and research before discussing them, as you seem to begin with Swing.
    Good luck.

  • About XML interop

    I Know that for using XML Interop I have to produce an XML file like that :
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <jdeRequest comment="" environment="PY812" pwd="xxxx" role="*ALL" session="" sessionidle="" type="callmethod" user="BUFFETAUD">
         <callMethod app="" name="LaunchBatchApplication">
              <returnCode code="0"/>
              <params>
                   <param name="szReport">R0006P</param>
                   <param name="szVersionJDE">XJDE0001</param>
                   <param name="cSynch">0</param>
                   <param name="cPrintPreview">0</param>
                   <param name="szDataSourceOverride"/>
                   <param name="mnServerJobNumber">0</param>
                   <param name="cReturn"/>
                   <param name="cJDELogging">0</param>
                   <param name="cTracing">0</param>
                   <param name="cUBELoggingLevel">1</param>
                   <param name="szJobQueue">QBATCH</param>
              </params>
         </callMethod>
    </jdeRequest>
    We are under JDE 8.12 Tools 8.98.2.3 and an AS400 V6R1.
    We are now using Oracle Data Ingrator 11G.
    I would like to know how and where to send using ODI this XML to make JDE execute my call?

    This is from Oracle.
    Please mark the answer as correct if you think it's right.
    JXMLTool (EnterpriseOne 8.98)
    Introduction:
    The JXMLTool is a GUI tool developed by Global Support Services to submit XML requests to ERP enterprise servers. The tool can be used to verify the integrity of the ERP services (kernel configuration, BSFN processing, among others) when testing inbound integrations from XPI and/or other third party systems to ERP. This document contains instructions on how to install and configure the tool.
    Installation and Configuration:
    1) Verify that a supported Java Development Kit (JDK) is installed in the workstation to be used in the test (for example, verify that JDK 1.4.2 is installed).
    Note: It is recommended that the workstation also have an EnterpriseOne 8.12 full client package installed.
    2) Create a new directory in the workstation (for example, C:\JXMLTool).
    3) Copy the following files from the Deployment server to the directory created in step 2:
    e812\system\classes\Base_JAR.jar
    e812\system\classes\JdeNet_JAR.jar
    e812\system\classes\System_JAR.jar
    e812\system\classes\log4j.jar
    e812\system\classes\xerces.jar
    e812\system\classes\xalan.jar
    e812\system\classes\ManagementAgent_JAR.jar
    e812\system\classes\jmxri.jar
    e812\system\classes\commons-httpclient-3.0.jar
    e812\system\classes\commons-logging.jar
    e812\system\classes\ xmlparserv2.jar
    e812\system\classes\ jmxremote_optional.jar
    e812\system\Classes\samples\jdeinterop.ini.templ
    e812\system\Classes\samples\jdelog.properties
    Note: If you have multiple-foundation implemented in the system, make sure the files you are copying match the service pack level installed in the enterprise server.
    4) Rename jdeinterop.ini.templ to jdeinterop.ini. Modify the jdeinterop.ini file copied in step 3 to reflect the correct enterprise server name:
    a) Ensure that parameters glossaryTextServer in [SERVER] section, serviceNameConnect in [JDENET] section, and enterpriseServer, port in [INTEROP] section specify the correct enterprise server name and JDENET port number).
    b) Configure the value of Repository under [INTEROP] section such that it points to the directory created in step 2 (for example, “Repository= C:\JXMLTool”).
    c) Ensure that parameter SecurityServer in [SECURITY] section specify the correct security server.
    d) Configure OCMEnabled to “false” in [OCM] section.
    e) Add the parameter netTrace to [JDENET] section and configure its value as “1” (for example, “netTrace=1”)
    5) Rename jdelog.properties.templ to jdelog.properties. Modify the jdelog.properties file to reflect the characteristics of the machine:
    a) Ensure that jdelog.handler.JDELOG.File points to directory created in step 2 (for example, jdelog.handler.JDELOG.File=C:/JXMLTool/jderoot.log).
    b) Ensure that jdelog.handler.JASLOG.File points to directory created in step 2 (for example, jdelog.handler.JASLOG.File=C:/JXMLTool/jas.log).
    c) Remove comment marks from parameters jdelog.Debug, jdelog.handler.jasdebug, jdelog.handler.jasdebug.File, and jdelog.handler.jasdebug.Level.
    c) Ensure that jdelog.handler.jasdebug.File points to directory created in step 2 (for example, jdelog.handler.jasdebug.File=C:/JXMLTool/jasdebug.log).
    6) Create a new text file using the text editor of your choice (for example, Notepad).
    7)Paste the following text to the new document:
    @echo off
    REM Edit this file to the locations for Java and EnterpriseOne
    REM JDK root directory
    set JAVA_HOME=C:\j2sdk1.4.2_12
    set PATH=C:\j2sdk1.4.2_12\bin
    REM EnterpriseOne Windows client install path
    set OneWorld_HOME=C:\e812
    REM This directory
    set EXAMPLES=C:\Interop\JXMLTool
    REM Set the CLASSPATH environment variable.
    REM The following are libraries that are needed for Connector samples:
    set CLASSPATH=Base_JAR.jar
    set CLASSPATH=%CLASSPATH%;C:\Interop\JXMLTool\
    set CLASSPATH=%CLASSPATH%;C:\Interop\JXMLTool\JXMLTool.class
    set CLASSPATH=%CLASSPATH%;JdeNet_JAR.jar
    set CLASSPATH=%CLASSPATH%;System_JAR.jar
    set CLASSPATH=%CLASSPATH%;log4j.jar
    set CLASSPATH=%CLASSPATH%;xerces.jar
    set CLASSPATH=%CLASSPATH%;xalan.jar
    set CLASSPATH=%CLASSPATH%;ManagementAgent_JAR.jar
    set CLASSPATH=%CLASSPATH%;jmxri.jar
    set CLASSPATH=%CLASSPATH%;commons-httpclient-3.0.jar
    set CLASSPATH=%CLASSPATH%;commons-logging.jar
    set CLASSPATH=%CLASSPATH%;xmlparserv2.jar
    set CLASSPATH=%CLASSPATH%;jmxremote_optional.jar
    set CLASSPATH=%CLASSPATH%;%OneWorld_HOME%\system\classes\
    a) Ensure that "set JAVA_HOME" command sets the variable with correct path to JDK directory (for example, "set JAVA_HOME=c:\jdk142").
    b) Configure value of OneWorld_HOME such that it points to the directory where OneWorld® is installed (for example, “set OneWorld_HOME=C:\e812”).
    c) Ensure that "set EXAMPLES" command sets the variable with the correct path to directory created in step 2 (for example, "set EXAMPLES=C:\JXMLTool").
    d) Configure value of JDEINTEROPINI such that it points to the jdeinterop.ini file you copied in step 3 (for example,
    “set JDEINTEROPINI=%EXAMPLES%\jdeinterop.ini”).
    e) Append the path of the bin directory of the JDK to the PATH variable. For example, add the following line:
    “set PATH=%JAVA_HOME%\bin”
    8) Save the file as setenv.bat in the directory created in step 2 (for example, C:\JXMLTool\setEnv.bat).
    9) Create a new text file using the text editor of your choice (for example, Notepad).
    10) Paste the following text to the new document:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.GregorianCalendar;
    import java.util.Date;
    import javax.swing.JOptionPane;
    import javax.swing.JFrame;
    import com.jdedwards.system.xml.XMLRequest;
    import com.jdedwards.system.net.JdeNetTimeoutException;
    import com.jdedwards.system.net.JdeNetConnectFailedException;
    // Application: JXMLTool
    // Description: Java tool that submits XML requests to OneWorld® enterprise Servers
    // Author: Luis A. Santillo
    public class JXMLTool extends JFrame implements ActionListener {         
    Panel xmlPanel;
    Label ServerNameLabel;
    Label PortNumberLabel;
    TextField PortNumberField;
    TextField ServerNameField;
    TextArea RequestArea;
    TextArea ReplyArea;
    Button submitButton;
    String directory;
    String owServerName;
    String ReplyString;
    int owPortNumber;
    MenuBar mb = new MenuBar();
    Menu fileMenu = new Menu("File");
    Menu helpMenu = new Menu("Help");
    MenuItem openMenuItem = new MenuItem("Open");
    MenuItem exitMenuItem = new MenuItem("Exit");
    MenuItem helpMenuItem = new MenuItem("About");
    public static void main(String args[]) {
    JXMLTool jxmltool = new JXMLTool();
    jxmltool.init();
    public void init () {
    xmlPanel = createXMLPanel();
    this.setSize(640, 480);
    this.setResizable(true);
    this.getContentPane().add(xmlPanel, BorderLayout.CENTER);
    this.setVisible(true);
    openMenuItem.addActionListener(this);
    fileMenu.add(openMenuItem);
    fileMenu.add(new MenuItem("-"));
    exitMenuItem.addActionListener(this);
    fileMenu.add(exitMenuItem);
    helpMenu.add(helpMenuItem);
    mb.add(fileMenu);
    mb.add(helpMenu);
    this.setMenuBar(mb);
    submitButton.addActionListener(this);
    directory = System.getProperty("user.dir");
    private Panel createXMLPanel()
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints constraints = new GridBagConstraints();
    xmlPanel = new Panel();
    xmlPanel.setLayout(gridbag);
    buildConstraints(constraints, 0, 0, 1, 1, 10, 5);
    constraints.fill = GridBagConstraints.NONE;
    ServerNameLabel = new Label("OneWorld® Server Name", Label.LEFT);
    gridbag.setConstraints(ServerNameLabel, constraints);
    xmlPanel.add(ServerNameLabel);
    buildConstraints(constraints, 1, 0, 1, 1, 40, 0);
    constraints.fill = GridBagConstraints.NONE;
    ServerNameField = new TextField("", 20);
    gridbag.setConstraints(ServerNameField, constraints);
    xmlPanel.add(ServerNameField);
    buildConstraints(constraints, 2, 0, 1, 1, 10, 0);
    constraints.fill = GridBagConstraints.NONE;
    PortNumberLabel = new Label("Port Number", Label.LEFT);
    gridbag.setConstraints(PortNumberLabel, constraints);
    xmlPanel.add(PortNumberLabel);
    buildConstraints(constraints, 3, 0, 1, 1, 40, 0);
    constraints.fill = GridBagConstraints.NONE;
    PortNumberField = new TextField("", 20);
    gridbag.setConstraints(PortNumberField, constraints);
    xmlPanel.add(PortNumberField);
    buildConstraints(constraints, 0, 1, 4, 1, 0, 40);
    constraints.fill = GridBagConstraints.BOTH;
    RequestArea = new TextArea("", 10, 80);
    gridbag.setConstraints(RequestArea, constraints);
    xmlPanel.add(RequestArea);
    buildConstraints(constraints, 0, 2, 4, 1, 0, 5);
    constraints.fill = GridBagConstraints.NONE;
    submitButton = new Button("Submit");
    gridbag.setConstraints(submitButton, constraints);
    xmlPanel.add(submitButton);
    buildConstraints(constraints, 0, 3, 4, 1, 0, 40);
    constraints.fill = GridBagConstraints.BOTH;
    ReplyArea = new TextArea("", 10, 80);
    ReplyArea.setBackground(Color.gray);
    gridbag.setConstraints(ReplyArea, constraints);
    xmlPanel.add(ReplyArea);
    return xmlPanel;
    void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy) {
    gbc.gridx = gx;
    gbc.gridy = gy;
    gbc.gridwidth = gw;
    gbc.gridheight = gh;
    gbc.weightx = wx;
    gbc.weighty = wy;
    public void actionPerformed(ActionEvent e) {
    if (e.getSource() instanceof MenuItem) {
    String label = ((MenuItem)e.getSource()).getLabel();
    if (label.equals("File"));
    if (label.equals("Open")) {
    FileDialog f = new FileDialog(this, "Open File", FileDialog.LOAD);
    f.setDirectory(directory);
    f.show();
    directory = f.getDirectory();
    setFile(directory, f.getFile());
    f.dispose();
    if (label.equals("Exit"))
    System.exit(0);
    if (label.equals("About"));
    if (e.getSource() instanceof Button) {
    if (ServerNameField.getText().equals(""))
    ReplyArea.setText("Error: server name is either null or empty!\nPlease enter new server name.\n");
    else {
    if (PortNumberField.getText().equals(""))
    ReplyArea.setText("Error: port number is either null or empty!\nPlease enter new port number.\n");
    else {
    owServerName = ServerNameField.getText();
    try {
    owPortNumber = Integer.parseInt(PortNumberField.getText());
    ReplyString = submitXMLRequest(RequestArea.getText());
    ReplyArea.setText(ReplyArea.getText() + "\n\n" + ReplyString);
    catch (NumberFormatException nfex) {
    ReplyArea.setText("Error: unable to format port number!\n");
    ReplyArea.setText(ReplyArea.getText() + "Exception: " + nfex +"\nPlease enter new port number.\n");
    public void setFile(String directory, String filename) {
    if ((filename == null) || (filename.length() == 0)) return;
    File f;
    FileReader in = null;
    try {
    f = new File(directory, filename);
    in = new FileReader(f);
    int size = (int) f.length();
    char[] data = new char[size];
    int chars_read = 0;
    while(chars_read < size)
    chars_read += in.read(data, chars_read, size-chars_read);
    RequestArea.setText(new String(data));
    catch (IOException e) {
    ReplyArea.setText(e.getClass().getName() + ": " + e.getMessage());
    finally { try { if (in != null) in.close(); } catch (IOException e) {} }
    public String submitXMLRequest(String xmlIn) {
    GregorianCalendar gregCalendar = new GregorianCalendar();
    String xmlOut = null;
    Date currentDate;
    try {
    ReplyArea.setText(gregCalendar.getTime() + " New XML request.\n");
    ReplyArea.setText(ReplyArea.getText() + gregCalendar.getTime() + " Creating XML request using text in area above.\n");
    XMLRequest xml = new XMLRequest(owServerName, owPortNumber, xmlIn);
    ReplyArea.setText(ReplyArea.getText() + gregCalendar.getTime() + " XML request submitted to " + owServerName + " using port number " + PortNumberField.getText() + ".\n");
    ReplyArea.setText(ReplyArea.getText() + gregCalendar.getTime() + " Waiting for reply from " + owServerName + ".\n");
    xmlOut = xml.execute();
    catch (JdeNetTimeoutException toex) {
    ReplyArea.setText(ReplyArea.getText() + "\nError: JDENet timed out!\n" + "Exception: " + toex +"\n\n");
    catch (JdeNetConnectFailedException cfex) {
    ReplyArea.setText(ReplyArea.getText() + "\nError: JDENet connect failed!\n" + "Exception: " + cfex +"\n\n");
    catch (java.io.IOException ioex) {
    ReplyArea.setText(ReplyArea.getText() + "\nError: IO Exception!\n" + "Exception: " + ioex +"\n\n");
    currentDate = new Date ();
    gregCalendar.setTime(currentDate);
    ReplyArea.setText(ReplyArea.getText() + gregCalendar.getTime() + " Reply received from " + owServerName + ".\n");
    return xmlOut;
    public void processWindowEvent(WindowEvent e) {
    if (e.getID() == Event.WINDOW_DESTROY) {
    System.exit(0);
    11) Save the file as JXMLTool.java in the directory created in step 2 (for example, C:\JXMLTool\JXMLTool.java).
    12) Create a new text file using the text editor of your choice (for example, Notepad).
    13) Paste the following text to the new document:
    @echo off
    call setenv.bat
    javac JXMLTool.java
    14) Save the file as build.bat in the directory created in step 2 (for example, C:\JXMLTool\build.bat).
    15) Build the JXMLTool Java application:
    a) Open a new MS-DOS Command Prompt window.
    b) Change the current directory to the directory created in step 2.
    c) Call the build.bat script to compile the Java code and create the JXMLTool Java class.
    d) Verify that JXMLTool.class exists in the directory created in step 2 (for example,
    “C:\JXMLTool\JXMLTool.class”).
    16) Create a new text file using the text editor of your choice (for example, Notepad).
    17) Paste the following text to the new document:
    @echo off
    call setenv.bat
    java -Dconfig_file=jdeinterop.ini JXMLTool
    18) Save the file as run.bat in the directory created in step 2 (for example, C:\JXMLTool\run.bat).
    Usage:
    1) Open a new MS-DOS Command Prompt window.
    2) Change the current directory to the directory created in step 2.
    3) Call the run.bat script to execute the JXMLTool Java application.
    5) In the Java application, enter enterprise server name and port number in appropriate text fields.
    6) Enter the following text in the upper panel:
    <?xml version='1.0' ?>
    <jdeRequest type='callmethod' user='JDE' pwd='JDE' environment='JPD812' session=''>
    <callMethod name='GetEffectiveAddress' app='JXMLTool'>
    <params>
    <param name='mnAddressNumber'>1001</param>
    </params>
    </callMethod>
    </jdeRequest>
    7) Modify the XML information to reflect the characteristics of the system:
    a) Replace user, password, and environment with correct values for your system.
    b) If 1001 is not a valid AddressBook number, replace it with a valid AB number.
    8) Click the button “Submit”.
    9) Verify that an XML reply is received from enterprise server. The reply will be displayed in the lower panel.
    Retrieving an XML Template for BSFN Request:
    1) Repeat steps 1 through 9 in Usage, using the following text in step 6:
    <?xml version='1.0' ?>
    <jdeRequest type='callmethod' user='JDE' pwd='JDE' environment='JPD812'>
    <callMethodTemplate name='GetEffectiveAddress' app='JXMLTool'/>
    </jdeRequest>
    2) Highlight the text in the lower panel, starting with tag “<?xml version='1.0' ?>”.
    3) Press Control (Ctrl) and C keys simultaneously.
    4) Open a new text document using the text editor of your choice.
    5) Paste contents into new text document.
    6) Remove tag “<returnCode=’0’/>”.
    7) Save text document with extension .xml.

  • Seems to be okay but something woring in terms of performance (about GUI)

    I have worked on some code on my textbook. I think everything seems to be fine but something is wrong.
    I tried to figure out this code but unfortunately I couldn't.
    'doTraitTest' facilitator doesn't act at all.
    Please give me any advice and thanks in advance.
    Here is the code that gave me a headache.
    // A simple psychometric-like type tool
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TypeIndicator {
    // class constants
    private final int WINDOW_WIDTH = 400;
    private final int WINDOW_HEIGHT = 325;
    private final int TEXT_WIDTH = 30;
    private final String LEGEND =
    "A series of preferences are asked. The responses are "
    + "used to determine a personality type profile. The tool "
    + "is primitive and is meant for fun. You should not make "
    + "any decisions based on its analysis. ";
    // instance GUI variable
    private JFrame window = new JFrame("Type Indicator");
    private JTextArea legendArea = new JTextArea(LEGEND, 4, TEXT_WIDTH);
    private JTextArea resultArea = new JTextArea();
    private JTextField statementPad = new JTextField("", TEXT_WIDTH);
    private JRadioButton trueButton = new JRadioButton("True ");
    private JRadioButton falseButton = new JRadioButton("False");
    private JRadioButton hiddenButton = new JRadioButton("False");
    private ButtonGroup buttonGroup = new ButtonGroup();
    // instant test variables
    private boolean introvert;
    private boolean senser;
    private boolean thinker;
    private boolean judger;
    public static void main(String [] args){
    TypeIndicator testInstrument = new TypeIndicator();
    // Typeindicator():default constructor
    public TypeIndicator () {
    configureAndDisplayGUI();
    introvert = isIntroversionDominant();
    senser = isSensingDominant();
    thinker = isThinkingDominant();
    judger = isJudgingDominant();
    presentResults();
    // configureAndDisplayGUI(): set up the GUI
    private void configureAndDisplayGUI (){
    // configure elements
    window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    legendArea.setEditable(false);
    legendArea.setLineWrap(true);
    legendArea.setWrapStyleWord(true);
    legendArea.setBackground(window.getBackground());
    statementPad.setVisible(false);
    statementPad.setEditable(false);
    statementPad.setHorizontalAlignment(SwingConstants.CENTER);
    statementPad.setBackground(window.getBackground());
    trueButton.setVisible(false);
    falseButton.setVisible(false);
    buttonGroup.add(trueButton);
    buttonGroup.add(falseButton);
    resultArea.setEditable(false);
    resultArea.setBackground(window.getBackground());
    // add elements to window's content pane
    window.setLayout(new FlowLayout());
    window.add(legendArea);
    window.add(statementPad);
    window.add(trueButton);
    window.add(falseButton);
    window.add(resultArea);
    // ready to display GUI
    window.setVisible(true);
    //isIntroversionDominant():is introversion dominant to extroversion
    private boolean isIntroversionDominant() {
    String s1 = "I prefer renting a video to going to a party.";
    String s2 = "I am happy when house guests leave.";
    String s3 = "Meeting new people makes me tense.";
    String s4 = "I enjoy being alone.";
    String s5 = "Crowd suck the life out of me.";
    return doTraitTest (s1, s2, s3, s4, s5);
    private boolean isSensingDominant() {
    String s1 = "Facts are more interesting than ideas";
    String s2 = "I need the details more than the big picture.";
    String s3 = "I always measure, I never estimate";
    String s4 = "Seeing is believing";
    String s5 = "If you cannot touch it, it's not real.";
    return doTraitTest (s1, s2, s3, s4, s5);
    private boolean isThinkingDominant() {
    String s1 = "I prefer page 1 to the comics in a newspaper";
    String s2 = "I think therefore I am.";
    String s3 = "I am not an emotional person";
    String s4 = "Tears will not cause me to change my mind";
    String s5 = "I'd rather be Data than Troi";
    return doTraitTest (s1, s2, s3, s4, s5);
    private boolean isJudgingDominant() {
    String s1 = "It is easy to make a decision";
    String s2 = "My first impressions are usually right";
    String s3 = "Wrong decisions are better than none.";
    String s4 = "I seldom have second thougths";
    String s5 = "Uncertainty makes me uncomfortable";
    return doTraitTest (s1, s2, s3, s4, s5);
    // doTraitTest(): test for dominant response for a type category
    private boolean doTraitTest(String s1, String s2, String s3,
    String s4, String s5) {
    // create running totals for responses
    int choiceTrue = 0;
    int choiceFalse = 0;
    // pose queries and get responses
    if (getTrueorFalseResponse(s1)) {
    ++choiceTrue;
    else {
    ++choiceFalse;
    if (getTrueorFalseResponse(s2)){
    ++choiceTrue;
    else {
    ++choiceFalse;
    if (getTrueorFalseResponse(s3)){
    ++choiceTrue;
    else {
    ++choiceFalse;
    if (getTrueorFalseResponse(s4)){
    ++choiceTrue;
    else {
    ++choiceFalse;
    if (getTrueorFalseResponse(s5)){
    ++choiceTrue;
    else {
    ++choiceFalse;
    // produce test result
    return choiceTrue > choiceFalse;
    // getTrueorFalseResponse(); pose a statement and get response
    private boolean getTrueorFalseResponse(String statement) {
    statementPad.setText(statement);
    hiddenButton.setSelected(true);
    statementPad.setVisible(true);
    trueButton.setVisible(true);
    falseButton.setVisible(true);
    for(; ;) {
    if(trueButton.isSelected() || falseButton.isSelected()){
    break;
    statementPad.setVisible(false);
    trueButton.setVisible(false);
    falseButton.setVisible(false);
    return trueButton.isSelected();
    // presentResult(): display testing results
    private void presentResults() {
    // setup text
    String result = "Your type is \n"
    + " "
    + ((introvert) ? "I" : "E")
    + ((senser) ? "S": "N")
    + ((thinker) ? "T": "F")
    + ((judger) ? "J": "P")
    + "\n"
    + "where\n"
    + "* E = extroversion \n"
    + "* I = introversion \n"
    + "* S = sensing \n"
    + "* N = intuitive \n"
    + "* T = thinking \n"
    + "* F = feeling \n"
    + "* J = judgment \n"
    + "* P = perception \n"
    + "\n"
    + " Thank you for trying the tool";
    // display test and quit button
    resultArea.setText(result);
    window.setVisible(true);

    Sorry about it. Hope this is better for you to read.
    // A simple psychometric-like type tool
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TypeIndicator {
        // class constants
        private final int WINDOW_WIDTH = 400;
        private final int WINDOW_HEIGHT = 325;
        private final int TEXT_WIDTH = 30;
        private final String LEGEND =
        "A series of preferences are asked. The responses are "
        + "used to determine a personality type profile. The tool "
        + "is primitive and is meant for fun. You should not make "
        + "any decisions based on its analysis. ";
        // instance GUI variable
        private JFrame window = new JFrame("Type Indicator");
        private JTextArea legendArea = new JTextArea(LEGEND, 4, TEXT_WIDTH); //parameters : String, rows, and columns
        private JTextArea resultArea = new JTextArea();
        private JTextField statementPad = new JTextField("", TEXT_WIDTH);
        private JRadioButton trueButton = new JRadioButton("True ");
        private JRadioButton falseButton = new JRadioButton("False");
        private JRadioButton hiddenButton = new JRadioButton("False");
        private ButtonGroup buttonGroup = new ButtonGroup();
        // instant test variables
        private boolean introvert;
        private boolean senser;
        private boolean thinker;
        private boolean judger;
        public static void main(String [] args){
            TypeIndicator testInstrument = new TypeIndicator();
        // Typeindicator():default constructor
        public TypeIndicator () {
            configureAndDisplayGUI();
            introvert = isIntroversionDominant();
            senser = isSensingDominant();
            thinker = isThinkingDominant();
            judger = isJudgingDominant();
            presentResults();
        // configureAndDisplayGUI(): set up the GUI
        private void configureAndDisplayGUI (){
            // configure elements
            window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            legendArea.setEditable(false);
            legendArea.setLineWrap(true);
            legendArea.setWrapStyleWord(true);
            legendArea.setBackground(window.getBackground());
            statementPad.setVisible(false);
            statementPad.setEditable(false);
            statementPad.setHorizontalAlignment(SwingConstants.CENTER);
            statementPad.setBackground(window.getBackground());
            trueButton.setVisible(false);
            falseButton.setVisible(false);
            buttonGroup.add(trueButton);
            buttonGroup.add(falseButton);
            resultArea.setEditable(false);
            resultArea.setBackground(window.getBackground());
            // add elements to window's content pane
            window.setLayout(new FlowLayout());
            window.add(legendArea);
            window.add(statementPad);
            window.add(trueButton);
            window.add(falseButton);
            window.add(resultArea);
            // ready to display GUI
            window.setVisible(true);
        //isIntroversionDominant():is introversion dominant to extroversion
        private boolean isIntroversionDominant() {
            String s1 = "I prefer renting a video to going to a party.";
            String s2 = "I am happy when house guests leave.";
            String s3 = "Meeting new people makes me tense.";
            String s4 = "I enjoy being alone.";
            String s5 = "Crowd suck the life out of me.";
            return doTraitTest (s1, s2, s3, s4, s5);
        private boolean isSensingDominant() {
            String s1 = "Facts are more interesting than ideas";
            String s2 = "I need the details more than the big picture.";
            String s3 = "I always measure, I never estimate";
            String s4 = "Seeing is believing";
            String s5 = "If you cannot touch it, it's not real.";
            return doTraitTest (s1, s2, s3, s4, s5);
        private boolean isThinkingDominant() {
            String s1 = "I prefer page 1 to the comics in a newspaper";
            String s2 = "I think therefore I am.";
            String s3 = "I am not an emotional person";
            String s4 = "Tears will not cause me to change my mind";
            String s5 = "I'd rather be Data than Troi";
            return doTraitTest (s1, s2, s3, s4, s5);
        private boolean isJudgingDominant() {
            String s1 = "It is easy to make a decision";
            String s2 = "My first impressions are usually right";
            String s3 = "Wrong decisions are better than none.";
            String s4 = "I seldom have second thougths";
            String s5 = "Uncertainty makes me uncomfortable";
            return doTraitTest (s1, s2, s3, s4, s5);
        // doTraitTest(): test for dominant response for a type category
        private boolean doTraitTest(String s1, String s2, String s3,
        String s4, String s5) {
            // create running totals for responses
            int choiceTrue = 0;
            int choiceFalse = 0;
            // pose queries and get responses
            if (getTrueorFalseResponse(s1)) {
                ++choiceTrue;
            else {
                ++choiceFalse;
            if (getTrueorFalseResponse(s2)){
                ++choiceTrue;
            else {
                ++choiceFalse;
            if (getTrueorFalseResponse(s3)){
                ++choiceTrue;
            else {
                ++choiceFalse;
            if (getTrueorFalseResponse(s4)){
                ++choiceTrue;
            else {
                ++choiceFalse;
            if (getTrueorFalseResponse(s5)){
                ++choiceTrue;
            else {
                ++choiceFalse;
            // produce test result
            return choiceTrue > choiceFalse;
            // getTrueorFalseResponse(); pose a statement and get response
            private boolean getTrueorFalseResponse(String statement) {
                statementPad.setText(statement);
                hiddenButton.setSelected(true);
                statementPad.setVisible(true);
                trueButton.setVisible(true);
                falseButton.setVisible(true);
                for(; ;) {
                    if(trueButton.isSelected() || falseButton.isSelected()){
                        break;
                statementPad.setVisible(false);
                trueButton.setVisible(false);
                falseButton.setVisible(false);
                return trueButton.isSelected();
            // presentResult(): display testing results
            private void presentResults() {
                // setup text
                String result = "Your type is \n"
                + "   "
                + ((introvert) ? "I" : "E")
                + ((senser) ? "S": "N")
                + ((thinker) ? "T": "F")
                + ((judger) ? "J": "P")
                + "\n"
                + "where\n"
                + "* E = extroversion \n"
                + "* I = introversion \n"
                + "* S = sensing \n"
                + "* N = intuitive \n"
                + "* T = thinking \n"
                + "* F = feeling \n"
                + "* J = judgment \n"
                + "* P = perception \n"
                + "\n"
                + " Thank you for trying the tool";
                // display test and quit button
                resultArea.setText(result);
                window.setVisible(true);
    }

  • JFrame setBackground(Color c)

    i'm just curious about Swing so i started reading sun tut Using Swing Components /Using Top-Level Containers and at the same time reviewing a tut i built some time ago called DiveLog (also from sun).
    package divelog;
    import javax.swing.*;
    import java.awt.*;   // Contains all of the classes for creating user
                         // interfaces and for painting graphics and images.
    import java.awt.event.*; // Provides interfaces and classes for
                             // dealing with different types of events fired by AWT components
    public class DiveLog {
        private JFrame dlframe;
        //private JTabbedPane tabbedPane;
        public DiveLog() {
            JFrame.setDefaultLookAndFeelDecorated(true);
            dlframe = new JFrame ("T?tulo do frame");
            dlframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            dlframe.setSize(400, 200);
            //dlframe.setBackground(Color(49, 106, 197));
            Color c = new Color(49, 106, 197);
            dlframe.setBackground(c);
            //dlframe.setForeground(c);
            //dlframe.pack();
            // Causes this Window to be sized to fit the
            // preferred size and layouts of its subcomponents.
            // If the window and/or its owner are not yet displayable,
            // both are made displayable before calculating the preferred size.
            // The Window will be validated after the preferredSize is calculated.
            dlframe.setVisible(true);
            System.out.print(dlframe.getBackground());
        public static void main(String args[]) {
            DiveLog dl = new DiveLog();
    }My Q:
    what's the use of
    .setBackground(c); if we cant see it?

    The content pane is always painted over the JFrame. So you would set the background color of the content pane, not the frame. So, I agree with you, there is no need for that line of code.
    The only possible reason I could think of is that when using a slow computer the painting may not be done fast enough and you could get a flicker as the frame is painted and then the content pane.
    JFrame frame = new JFrame();
    frame.setBackground( Color.RED );
    frame.getContentPane().setBackground( Color.GREEN );
    frame.setSize(300, 300);
    frame.setVisible(true);
    Run the above code and you will notice a flicker as the frame is first painted red and then green. So to reduce flicker you could set the frame background to green as well. In most cases when using the default background color of gray you don't notice the flicker so you don't usually worry about it.

  • Question about JScrollPane

    Hi everybody,
    I'm using HSQLDB in my program and users can execute custom queries with a JTextArea. When an exception is thrown during the excecution of a big query, the message is pretty large, because it contains the query itself and the warnings/remarks about it.
    What I wanted to do was to use a JOptionPane and add the message to the JOptionPane inside a JScrollPane. I want the maximum size of the JScrollPane to be 320 x 160. This is what I'm doing now:
    Dimension size = new Dimension(320, 160);
    JLabel label = new JLabel(exception.getMessage());
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.getViewport().setLayout(new FlowLayout(0, 0, FlowLayout.LEFT));
    scrollPane.getViewport().add(label);
    scrollPane.getViewport().setMinimumSize(size);
    scrollPane.getViewport().setMaximumSize(size);
    scrollPane.getViewport().setPreferredSize(size);
    scrollPane.getViewport().setSize(size);
    scrollPane.getViewport().setBackground(Color.WHITE);
    JOptionPane.showMessageDialog(null, scrollPane, "Error", JOptionPane.ERROR_MESSAGE);I want no horizontal scrollbar, only a vertical. The problem with the code above is that the message stands on one line, instead to be spread on more then one line (thereby, you cannot see the message completely, because the horizontal scrollbar is disabled).
    The result I want is that the message is spread over more then one line, like in HTML when you've got a long text, the browser itself will spread the text over several lines that are available in the container where the text is in.
    Does somebody understand my problem? :-) I wish I could upload an image as an example, but FTP is blocked on the network where I'm connected to.
    Kind regards,
    Sweepee.
    Message was edited by:
    Sweepee

    see if this gets you close
    import java.awt.*;
    import javax.swing.*;
    class Testing
      public static void main(String[] args)
        JTextArea ta = new JTextArea();
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);
        ta.setText("I want no horizontal scrollbar, only a vertical. The problem with the"+
        " code above is that the message stands on one line, instead to be spread on more"+
        " then one line (thereby, you cannot see the message completely, because the"+
        " horizontal scrollbar is disabled).\n\nThe result I want is that the message is"+
        " spread over more then one line, like in HTML when you've got a long text, the"+
        " browser itself will spread the text over several lines that are available in the"+
        " container where the text is in.\n\nDoes somebody understand my problem? :-) I wish"+
        " I could upload an image as an example, but FTP is blocked on the network where I'm connected to.");
        JScrollPane scrollPane = new JScrollPane(ta);
        scrollPane.setPreferredSize(new Dimension(320, 160));
        JOptionPane.showMessageDialog(null, scrollPane, "Error", JOptionPane.ERROR_MESSAGE);
        System.exit(0);
    }

  • Question about relative sizing on JPanels

    Hi,
    My question is about relative sizing on components that are not drawn yet. For example I want to draw a JLabel on the 3rd quarter height of a JPanel. But JPanel's height is 0 as long as it is not drawn on the screen. Here is a sample code:
    JPanel activityPnl = new JPanel();
    private void buildActivityPnl(){
            //setting JPanel's look and feel
            activityPnl.setLayout(null);
            activityPnl.setBackground(Color.WHITE);
            int someValue = 30;  // I use this value to decide the width of my JPanel
            activityPnl.setPreferredSize(new Dimension(someValue, 80));
            //The JLabel's height is 1 pixel and its width is equal to the JPanel's width. I want to draw it on the 3/4 of the JPanel's height
            JLabel timeline = new JLabel();
            timeline.setOpaque(true);
            timeline.setBackground(Color.RED);
            timeline.setBounds(0, (activityPnl.getSize().height * 75) / 100 , someValue , 1);
            activityPnl.add(timeline);
        }Thanks a lot for your help
    SD
    Edited by: swingDeveloper on Feb 24, 2010 11:41 PM

    And use a layout manager. It can adjust automatically for a change in the frame size.
    Read the Swing tutorial on Using Layout Managers for examples of the different layout managers.

  • Please help - JFrame, menu, another JFrame, setBackground

    I am trying to make a simple program that draws a JFrame with a menu. The menu has one item, which when selected draws another JFrame. That JFrame has a button, which when pressed changes the background color. Many hours have gone into this, despite the fact that I made a similar program a few weeks ago.
    The compiler complains about the method getContentPane, when I remove that, it runs and draws the first window, but the menu item does not make the second window. Also, the setDefaultCloseOperation confuses the compiler as well.
    Please help.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MenuAction2
    public static void main(String[] args) 
         MainWindow window = new MainWindow("Menu action example");
      //window.setDefaultCloseOperation.(JFrame.EXIT_ON_CLOSE);
         window.setVisible(true);      
    class MainWindow extends JFrame
         MainWindow(String title)
         super(title);
         getContentPane.setLayout(new BorderLayout());
         Toolkit theKit = getToolkit();          
         Dimension wndSize = theKit.getScreenSize();  
         setBounds(0, 0,wndSize.width, wndSize.height);
         setJMenuBar(menuBar);
         fileMenu = new JMenu("File");
         connectItem = new JMenuItem();
         connectItem = fileMenu.add("Connect...");
         connectItem.addActionListener(menuHandler = new Handler());
         menuBar.add(fileMenu);
         getContentPane.add(toolBar, BorderLayout.NORTH);  
    class Handler implements ActionListener
         public void actionPerformed(ActionEvent e)
          win = new ConnectWindow("Connect to Database");
          getContentPane().add(win, BorderLayout.NORTH);
          setVisible(true);
      private JMenu fileMenu;
      private JMenuItem connectItem;
      private JMenuBar menuBar = new JMenuBar(); 
      private JToolBar toolBar = new JToolBar();
      private Handler menuHandler;
      private ConnectWindow win;
    class ConnectWindow extends JFrame
         ConnectWindow(String title)
              super(title);
              setSize(200,200);
              setLayout(new BorderLayout());
              JButton connectB = new JButton("Connect");
              connectB.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        setBackground(Color.red);
              add(connectB,BorderLayout.SOUTH);
              setVisible(true);
    }

    getContentPane is a method so you should use it that way:
    getContentPane().setLayout(new BorderLayout());
    getContentPane.add(new Button("Ok"));

Maybe you are looking for

  • Write xmp sidecar files without need to export masters - script

    I've written a script to write xmp sidecar files for referenced and online images (the 2 conditions in the script) of the selected images. I looked for a while at system events and other stuff to be able to write the xmp file, but i'm not a programme

  • Moving music files out of Shared User file

    Our iTunes has been set up so that all the music files are stored under the Shared User. We now only have one user on that computer. I want to move the iTunes over to a new computer but am having problems getting the music over since its not saved un

  • Standard MSI tvcard for 180 problems!

    Help! I don't seem to get any channel on my tv cards only thing i get is blue screens. I installed everything and try to autoscan in media portal deluxe and i only get blue screens. I am in holland and tryed every pal setting but it should be PAL_B (

  • How to add users to group which is present in another AD domain?

    Hi, Using JNDI how to add user as a member of group which is present in another AD domain? For example: In AD forest test.com their are two domain a.test.com and b.test.com. Group is present in a.test.com and I want to add user present in b.test.com

  • Forms 6i and OAS with Catridges deployment.

    I have installed both OAS and Forms 6i under the same Oracle Home. (NT 4.0. W/S SP 5, IE-5) I created the application (with forms cartidge) following the instructions. Neither the cgi not base.html are working. However, I am able to invoke jinitiator