JLabel Color

Can anyone tell me how to display the string in the statement below in a different color?
addComponent(entryPanel, new JLabel("(Must at least contain one character)"), layout, constraints, 1,y,1,1);

I'm going to guess that it would be:
JLabel label = new JLabel("(Must at least contain one character)");
label.setForeground(someColor); // where someColor is a java.awt.Color
addComponent(entryPanel, label, layout, constraints,1,y,1,1);

Similar Messages

  • Change MetalLookAndFeel JLabel Color?

    I am wanting to use the MetalLookAndFeel in my application, but want the color for all my JLabels to be Black instead of the purpleish color I understand how to create your own custom color themes but cannot find out how to change the JLabel color does anybody know what needs to be in myCustom theme that will change that color to black?

    Not sure if this is exactly what you are after but...
    JLabels are usually transparent to start with and show the underlying component's background colour. If you want to change the background, you have to set the color and then use setOpaque(true).

  • Easy JLabel color question

    I want all the labels on a JPanel in blue,
    is there a way to avoid to write each time?:
    label1.setForeground(Color.blue);
    label2.setForeground(Color.blue);
    label3.setForeground(Color.blue);
    label10.setForeground(Color.blue);
    I have try panel.setForeground(Color.blue);
    ..where panel is the container of the labels with no success.
    ?�

    You can always create a subclass of JLabel and have the default settings in the constructor to be blue. Then you just use these labels than the regular JLabels.
    I hope this helps.

  • JLabel multiple colors

    Hey all,
    I have a JLabel that says "Color 1: blue, Color 2: red" for example.
    I am having an issue with changing the color of JLabel so that the label reads "{color:#0000ff}Color 1: blue{color}, {color:#ff0000}Color 2: red{color}" all in one JLabel. If I chan the color for the start then add the secound bit of text then change the color again as expected it changes the whole JLabel color.
    Any help will be appreciated.

    I am having trouble with the html code for the JLabel the compiler doesn't seem to allow it.
    How can I make the compiler recognize that there is html code?
    JLabel color = new JLabel("<color="blue">Color 1</color><color="red">Color 2</color>");

  • Cannot display JLabel text in JTable

    Hi, This is a simple but frustrating little problem
    I am having trouble displaying the label text in a column of a JTable.
    I have hacked up a copy of TableDialogEditDemo.java from the tutorials
    on using JTables. This uses a renderer and editor models to deal with a
    column of colors.
    I have changed it to use JLabels instead. What want is for the label
    text to appear and when the user selects the cell be allowed to launch
    a dialog box (such as the demo program does with colorchooser).
    The dialog launching funcionalty works fine but the label text does not display.
    I end up with the column of JLabels as blank, even though the values
    are properly set. It seems like the TableCellRenderer doesn't display the
    controls text.
    I've spent the better part of two work days trying to get this one to work.
    Compiling and just running the code (without any interaction with the table)
    shows the problem. The second column of items will be blank instead of
    cells with text.
    Help!
    Thanks!
    /Steve McCauley
    Sanera Systems
    [email protected]
    Here is the code:
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.JLabel;
    import javax.swing.JDialog;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JColorChooser;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import java.awt.*;
    import java.awt.event.*;
    * This is like TableEditDemo, except that it substitutes a
    * Favorite Color column for the Last Name column and specifies
    * a custom cell renderer and editor for the color data.
    public class TableDialogEditDemo extends JFrame {
    private boolean DEBUG = false;
    public TableDialogEditDemo() {
    super("TableDialogEditDemo");
    MyTableModel myModel = new MyTableModel();
    JTable table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Set up renderer and editor for the Favorite Color column.
    setUpColorRenderer(table);
    setUpColorEditor(table);
    //Set up real input validation for integer data.
    setUpIntegerEditor(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class ColorRenderer extends JLabel
    implements TableCellRenderer {
    Border unselectedBorder = null;
    Border selectedBorder = null;
    boolean isBordered = true;
    public ColorRenderer(boolean isBordered) {
    super();
    this.isBordered = isBordered;
    // setOpaque(true); //MUST do this for background to show up.
    public Component getTableCellRendererComponent(
    JTable table, Object color,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    // setBackground((Color)color);
    setForeground(Color.black);
    setBackground(Color.white);
    System.out.println(" Label: " + ((JLabel)color).getText());
    if (isBordered) {
    if (isSelected) {
    if (selectedBorder == null) {
    selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getSelectionBackground());
    setBorder(selectedBorder);
    } else {
    if (unselectedBorder == null) {
    unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getBackground());
    setBorder(unselectedBorder);
    return this;
    private void setUpColorRenderer(JTable table) {
    table.setDefaultRenderer(JLabel.class,
    new ColorRenderer(true));
    //Set up the editor for the Color cells.
    private void setUpColorEditor(JTable table) {
    //First, set up the button that brings up the dialog.
    final JButton button = new JButton("") {
    public void setText(String s) {
    //Button never shows text -- only color.
    button.setBackground(Color.white);
    button.setBorderPainted(false);
    button.setMargin(new Insets(0,0,0,0));
    //Now create an editor to encapsulate the button, and
    //set it up as the editor for all Color cells.
    final ColorEditor colorEditor = new ColorEditor(button);
    table.setDefaultEditor(JLabel.class, colorEditor);
    //Set up the dialog that the button brings up.
    final JColorChooser colorChooser = new JColorChooser();
    ActionListener okListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    colorEditor.currentLabel = new JLabel("xxx");
    final JDialog dialog = JColorChooser.createDialog(button,
    "Pick a Color",
    true,
    colorChooser,
    okListener,
    null); //XXXDoublecheck this is OK
    //Here's the code that brings up the dialog.
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // button.setBackground(colorEditor.currentColor);
    // colorChooser.setColor(colorEditor.currentColor);
    //Without the following line, the dialog comes up
    //in the middle of the screen.
    //dialog.setLocationRelativeTo(button);
    dialog.show();
    * The editor button that brings up the dialog.
    * We extend DefaultCellEditor for convenience,
    * even though it mean we have to create a dummy
    * check box. Another approach would be to copy
    * the implementation of TableCellEditor methods
    * from the source code for DefaultCellEditor.
    class ColorEditor extends DefaultCellEditor {
    JLabel currentLabel = null;
    public ColorEditor(JButton b) {
    super(new JCheckBox()); //Unfortunately, the constructor
    //expects a check box, combo box,
    //or text field.
    editorComponent = b;
    setClickCountToStart(1); //This is usually 1 or 2.
    //Must do this so that editing stops when appropriate.
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fireEditingStopped();
    protected void fireEditingStopped() {
    super.fireEditingStopped();
    public Object getCellEditorValue() {
    return currentLabel;
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column) {
    ((JButton)editorComponent).setText(value.toString());
    currentLabel = (JLabel)value;
    return editorComponent;
    private void setUpIntegerEditor(JTable table) {
    //Set up the editor for the integer cells.
    final WholeNumberField integerField = new WholeNumberField(0, 5);
    integerField.setHorizontalAlignment(WholeNumberField.RIGHT);
    DefaultCellEditor integerEditor =
    new DefaultCellEditor(integerField) {
    //Override DefaultCellEditor's getCellEditorValue method
    //to return an Integer, not a String:
    public Object getCellEditorValue() {
    return new Integer(integerField.getValue());
    table.setDefaultEditor(Integer.class, integerEditor);
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Favorite Color",
    "Sport",
    "# of Years",
    "Vegetarian"};
    // final Object[][] data = {
    // {"Mary", new Color(153, 0, 153),
    // "Snowboarding", new Integer(5), new Boolean(false)},
    // {"Alison", new Color(51, 51, 153),
    // "Rowing", new Integer(3), new Boolean(true)},
    // {"Kathy", new Color(51, 102, 51),
    // "Chasing toddlers", new Integer(2), new Boolean(false)},
    // {"Mark", Color.blue,
    // "Speed reading", new Integer(20), new Boolean(true)},
    // {"Philip", Color.pink,
    // "Pool", new Integer(7), new Boolean(false)}
    final Object[][] data = {
    {"Mary", new JLabel("label-1"),
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", new JLabel("label-2"),
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", new JLabel("label-3"),
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", new JLabel("label-4"),
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Philip", new JLabel("label-5"),
    "Pool", new Integer(7), new Boolean(false)}
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 1) {
    return false;
    } else {
    return true;
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    public static void main(String[] args) {
    TableDialogEditDemo frame = new TableDialogEditDemo();
    frame.pack();
    frame.setVisible(true);

    You pretty much hit the nail on the head. Thank!
    Just didn't realize I needed to set the text of the component but with your
    tip and thinking about it, it makes sense.
    Actually I needed to use:
    setText(t_label.getText());
    Using toString got me: "java.swing......" (the components text representation)
    Thanks a bunch!
    /Steve

  • Rendering alternate colors in JTree

    I have a JTree within a scrollpane.
    What I would like to do is have every alternate line on the JTree rendered with one of 2 colors, i.e. line 1 is blue, line 2 is yellow, line 3 is blue etc.
    The tricky bit is that I want this color to fill the width of the scrollpane - changing the background of the JLabel color in the renderer will only update from the tree node to the right of the scrollpane (it leaves the area to the left of the node blank).
    Am I making any sense?

    Try this
    regards
    Stas
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.tree.*;
    public class Test {
    JScrollPane scroll;
    JTree tree;
    public Test() throws Exception {
    JFrame frame=new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    DefaultMutableTreeNode root=new DefaultMutableTreeNode("root");
    DefaultMutableTreeNode node1=new DefaultMutableTreeNode("node1");
    DefaultMutableTreeNode node2=new DefaultMutableTreeNode("node2");
    root.add(node1);
    root.add(node2);
    DefaultMutableTreeNode subnode2=new DefaultMutableTreeNode("node2_1");
    node2.add(subnode2);
    subnode2=new DefaultMutableTreeNode("node2_2");
    node2.add(subnode2);
    subnode2=new DefaultMutableTreeNode("node2_3");
    node2.add(subnode2);
    tree=new JTree(root);
    tree.setCellRenderer(new MyRenderer());
    frame.getContentPane().add(tree);
    frame.setBounds(100,100,200,200);
    frame.show();
    public static void main(String[] args) throws Exception {
    new Test();
    class MyRenderer extends DefaultTreeCellRenderer {
    public MyRenderer() {
    super();
    setOpaque(true);
    public Component getTreeCellRendererComponent(JTree tree, Object value,
    boolean sel,
    boolean expanded,
    boolean leaf, int row,
    boolean hasFocus) {
    JLabel l=(JLabel)super.getTreeCellRendererComponent(tree, value,
    sel,
    expanded,
    leaf, row,
    hasFocus);
    l.setPreferredSize(new Dimension(5000,20));
    if (row % 2==0) {
    l.setBackground(Color.CYAN);
    else {
    l.setBackground(Color.YELLOW);
    return l;

  • Help!  What is wrong with my code, these rectangles won't draw!!!!!!!!!!!!!

    I get no errors compiling
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    //<applet code="ShapePainter.class" width=500 height=500"></applet>
    public class ShapePainter extends JApplet implements ActionListener{
        pane g;
         //Shape Variables
         static public int squareWidth = 40;
         static public int squareHeight = 40;
         static public int squareStartX = 1;
         static public int squareStartY = 1;
         //Buttons
         JButton drawRects = new JButton("Draw Rectangle Background");
         JButton drawSquares = new JButton("Draw Square Background");
         public JButton black = new JButton("Black");
         JButton blue = new JButton("Blue");
         JButton cyan = new JButton("Cyan");
         JButton darkGray = new JButton("Dark Gray");
         JButton gray = new JButton("Gray");
         JButton green = new JButton("Green");
         JButton lightGray = new JButton("Light Gray");
         JButton magenta = new JButton("Magenta");
         JButton orange = new JButton("Orange");
         JButton pink = new JButton("Pink");
         JButton red = new JButton("Red");
         JButton white = new JButton("White");
         JButton yellow = new JButton("Yellow");
         JButton black2 = new JButton("Black");
         JButton blue2 = new JButton("Blue");
         JButton cyan2 = new JButton("Cyan");
         JButton darkGray2 = new JButton("Dark Gray");
         JButton gray2 = new JButton("Gray");
         JButton green2 = new JButton("Green");
         JButton lightGray2 = new JButton("Light Gray");
         JButton magenta2 = new JButton("Magenta");
         JButton orange2 = new JButton("Orange");
         JButton pink2 = new JButton("Pink");
         JButton red2 = new JButton("Red");
         JButton white2 = new JButton("White");
         JButton yellow2 = new JButton("Yellow");
         //Labels
         JLabel backGroundTypes = new JLabel("Back Ground Types:");
         JLabel colorOfBackgroundTypes = new JLabel("Color of BackgroundTypes:");
         JLabel colorOfBackground = new JLabel("Color of Background:");
         //intialize
         public void init(){
              Container contentPane = getContentPane();
              g = new pane();
              contentPane.add(g);
              //add components.
              g.add(backGroundTypes);
              g.add(drawRects);
              g.add(drawSquares);     
              g.add(colorOfBackgroundTypes);          
              g.add(black);
              g.add(blue);
              g.add(cyan);
              g.add(darkGray);
              g.add(gray);
              g.add(green);
              g.add(lightGray);
              g.add(magenta);
              g.add(orange);
              g.add(pink);
              g.add(red);
              g.add(white);
              g.add(yellow);
              g.add(colorOfBackground);
              g.add(black2);
              g.add(blue2);
              g.add(cyan2);
              g.add(darkGray2);
              g.add(gray2);
              g.add(green2);
              g.add(lightGray2);
              g.add(magenta2);
              g.add(orange2);
              g.add(pink2);
              g.add(red2);
              g.add(white2);
              g.add(yellow2);
              drawRects.addActionListener(this);
              drawSquares.addActionListener(this);
              black.addActionListener(this);
              blue.addActionListener(this);
              cyan.addActionListener(this);
              darkGray.addActionListener(this);
              gray.addActionListener(this);
              green.addActionListener(this);
              lightGray.addActionListener(this);
              magenta.addActionListener(this);
              orange.addActionListener(this);
              pink.addActionListener(this);
              red.addActionListener(this);
              white.addActionListener(this);
              yellow.addActionListener(this);
            //add ActionListeners
            black2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.black);
              blue2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.blue);
              cyan2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.cyan);
              darkGray2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.darkGray);
              gray2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.gray);
              green2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.green);
              lightGray2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.lightGray);
              magenta2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.magenta);
              orange2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.orange);
              pink2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.pink);
              red2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.red);
              white2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.white);
              yellow2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent event){
                        g.setBackground(Color.yellow);
         public void actionPerformed(ActionEvent e){
              if(e.getSource() == drawRects) {
                   for(int i = 0; i < 20; i++){
                        class drawR{
                             public int rectWidth = 50;
                             public int rectHeight = 100;
                             public int rectStartX = 1;
                             public int rectStartY = 1;
                             public void paint(Graphics r){                         
                                  r.drawRect(rectStartX, 300, rectWidth, rectHeight);     
                                  rectStartX = rectStartX + 50;     
                                 rectStartY = rectStartY + 50;
         class pane extends JPanel{
              pane(){                  
                        

    think this is what you intended,
    public void actionPerformed(ActionEvent e){
          if(e.getSource() == drawRects) {
             class drawR{
                public int rectWidth = 50;
                public int rectHeight = 100;
                public int rectStartX = 1;
                public int rectStartY = 1;
                public void paint(Graphics r){                         
                   r.drawRect(rectStartX, 100, rectWidth, rectHeight);
                   rectStartX = rectStartX + 50;     
                   rectStartY = rectStartY + 50;
             drawR dr = new drawR();
             for(int i = 0; i < 20; i++){
                dr.paint( g.getGraphics() );
          }                    

  • What is wrong with my Eclipse??

    Dear Sir:
    I have following problem in Eclipse 3.3.1
    When i run in Command console, It success all,
    But when I put into Eclipse, It fails, I got follwoing error:
    ERROR>java version "1.6.0"
    ERROR>Java(TM) SE Runtime Environment (build 1.6.0-b105)
    ERROR>Java HotSpot(TM) Client VM (build 1.6.0-b105, mixed mode)
    <GoodWinRedirect>ExitValue: 0
    ERROR>java.lang.NoClassDefFoundError: abc/LabelForComboBox
    ERROR>Exception in thread "main"
    What is wrong in my Eclipse Setting??
    How to fix it??
    Really Thanks
    see code below:
    [1]. Main Program
    import java.util.*;
    import java.io.*;
    public class GoodWinRedirect
        public static void main(String args[])
            if (args.length < 1)
                System.out.println("USAGE java GoodWinRedirect <outputfile>");
                System.exit(1);
            try
                FileOutputStream fos = new FileOutputStream(args[0]);
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("java  -version");
                Process proc1 = rt.exec("cmd /c java  abc/LabelForComboBox");
                // any error message?
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");           
                StreamGobbler errorGobbler1 = new StreamGobbler(proc1.getErrorStream(), "ERROR");           
                // any output?
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT", fos);
                StreamGobbler outputGobbler1 = new StreamGobbler(proc1.getInputStream(), "OUTPUT", fos);
                // kick them off
                errorGobbler.start();
                outputGobbler.start();
                errorGobbler1.start();
                outputGobbler1.start();
                  // any error???
                int exitVal = proc.waitFor();
                System.out.println("<GoodWinRedirect>ExitValue: " + exitVal);
                fos.flush();
                fos.close();       
            } catch (Throwable t)
                t.printStackTrace();
    }[2]. Sub 1 Program:
    package abc;
    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        OutputStream os;
        StreamGobbler(InputStream is, String type)
            this(is, type, null);
        StreamGobbler(InputStream is, String type, OutputStream redirect)
            this.is = is;
            this.type = type;
            this.os = redirect;
        public void run()
            try
                PrintWriter pw = null;
                if (os != null)
                    pw = new PrintWriter(os);
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null)
                    if (pw != null)
                        pw.println(line);
                    System.out.println(type + ">" + line);   
                if (pw != null)
                    pw.flush();
            } catch (IOException ioe)
                ioe.printStackTrace(); 
    }[3]. sub 2:
    package abc;
    import java.awt.Dimension;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.Box;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class LabelForComboBox extends JPanel {
      public LabelForComboBox() {
        JLabel lbl = new JLabel("Color:");
        lbl.setDisplayedMnemonic('c');
        add(lbl);
        add(Box.createHorizontalStrut(20));
        JComboBox cbColor = new JComboBox();
        cbColor.addItem("red");
        cbColor.addItem("blue");
        lbl.setLabelFor(cbColor);
        add(cbColor);
      public static void main(String[] a) {
        JFrame f = new JFrame("LabelForComboBox");
        f.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
        f.getContentPane().add(new LabelForComboBox());
        f.pack();
        f.setSize(new Dimension(300, 200));
        f.show();
    }

    Yes, I did this before and now, but fails, see:ERROR>java version "1.6.0"
    ERROR>Java(TM) SE Runtime Environment (build 1.6.0-b105)
    ERROR>Java HotSpot(TM) Client VM (build 1.6.0-b105, mixed mode)
    <GoodWinRedirect>ExitValue: 0
    ERROR>java.lang.NoClassDefFoundError: abc/LabelForComboBox
    ERROR>Exception in thread "main"
    looks weird.
    >
    You haven't changed it, OR
    You have pasted the old error message (unhelpful).
    Try again and paste the new error message. If the error reads as follows (note the / character after "abc") you have NOT changed the code to fix the class name:
    ERROR>java.lang.NoClassDefFoundError: abc/LabelForComboBox
    The class name used must be abc.LabelForComboBox because abc/LabelForComboBox cannot work.

  • Constructor problem with super keyword

    When I try to compile this class, I get 1 error:
    C:\Program Files\Xinox Software\JCreatorV3\MyProjects\FixedDiameterCircle.java:6: cannot resolve symbol
    symbol : constructor CircleGUI (int)
    location: class CircleGUI
    super(100);
    ^
    1 error
    class FixedDiameterCircle extends CircleGUI
         FixedDiameterCircle()
              super(100);     
         }//end FixedDiameterCircle()
    public void setDiameter(int d)
    }//end class FixedDiameterCircle
    ---------Here's the CircleGUI.java-------
    import javax.swing.*; //import Swing components
    import java.awt.*; //import awt components
    import java.awt.event.*; //import event handlers
    public class CircleGUI implements ActionListener
    JTextField diameter = new JTextField(3); //text field for first name
    JTextField color = new JTextField(5); //text field for last name
    JButton button = new JButton("Draw"); //update button
    JPanel panel = new JPanel(); //panel for frame content pane
    JFrame frame = new JFrame("Draw"); //frame for window + title
    public CircleGUI()
    panel.add(new JLabel("Diameter")); //add a label to panel
    panel.add(diameter); //add first to panel
    panel.add(new JLabel("Color")); //add another label to panel
    panel.add(color); //add a last to panel
    button.addActionListener(this); //add a click listener to button
    panel.add(button); //add button to panel
    frame.setContentPane(panel); //set panel as frame's content
    frame.setSize(120, 120); //set frame size (width, height)
    frame.setVisible(true); //make frame visible
    }//end CircleGUI()
    public void actionPerformed(ActionEvent e)//executed when button is clicked
    int d = Integer.parseInt(diameter.getText()); //get diameter
    Circle circle; //declare Circle variable
    if(color.getText().length() == 0) //if no color entered in field
    {                                       //use JColorChooser below
    Color rgb = JColorChooser.showDialog(frame, "Choose a Color", null);
    if(rgb != null) //if Color rgb chosen
    circle = new Circle(d,rgb); //instantiate Circle from Color
    }//end if(color...
    else
    String c = color.getText(); //get color String
    circle = new Circle(d,c); //instantiate Circle from String
    }//end else
    }//end actionPerformed()
    public static void main(String[] args) //main method
    CircleGUI cGUI = new CircleGUI(); //instantiate CircleGUI
    }//end main()
    }//end class CircleGUI
    What's the problem?

    CircleGUI does not have a constructor that takes an int. You need to either add this to CircleGui:public CircleGui(int diameter) { /* do stuff */ } or just cal super() instead of super(int). Which one is better is left as an exercise for the reader.

  • 1.4.2 vs 1.4.1_02 speed comparison

    Houston, we have a problem....
    I have a swing applet(JFrame) that updates 1800 JLabel boxes(yes they are tiny, no text) with a color.
    1.4.1_02 is about 8 times faster than 1.4.2 to initially update the screen after it displays
    by changing all the JLabel colors based on the data sent via socket connection from the server.
    I recompiled with 1.4.2 jsdk and loaded 1.4.2 jre on my win NT4.0sp6/Netscape 4.76 pc,
    updated my applet code for 1.4.2 plugins.
    1.4.1_01 takes about 2 seconds, 1.4.2 takes 10 seconds.
    If this is an indication of whats to come in 1.5, i'll be stuck with 1.4.1_02 forever.
    However, other applets that display a 2 megabyte JTable seem to be the same speed.
    No errors in java console.
    Does anybody see speed problems with JLabels or swing components in general?

    Perhaps you should create a test case and submit a bug against 1.4.2 indicating that it's a performance regression.

  • Refreshing a set of JPanels

    Hello there,
    I have an issue with refreshing and replacing my JPanel colors. As you can see, the format is GridLayout with the size of the grid changing based on what file they open. My issue is that when a second file is opened, it merely adds those JPanels to the end of the previously loaded set of JPanels. I've tried refresh() and repaint() but to no avail. Maybe I placed them in the wrong place, not sure. Thanks in advance.
              if (actionCommand.equals("Open..."))
                   JFileChooser fileChooser = new JFileChooser();
                   fileChooser.setDialogTitle("Choose a file");
                   this.getContentPane().add(fileChooser);
                   fileChooser.setVisible(true);
                   int result = fileChooser.showOpenDialog(this);
                   File file = fileChooser.getSelectedFile();
                   GridMap gm = new GridMap();
                   gm.read(file);
                   int row = gm.getRow();
                   int col = gm.getColumn();
                   setLayout(new GridLayout(row,col));
                   for (int i = 0; i < row; i++)
                        for (int j = 0; j < col; j++)
                             JLabel color = new JLabel();
                             color.setOpaque(true);
                             if (gm.getGrid(i,j) == 'O')
                                  color.setBackground(Color.GREEN);
                             else if (gm.getGrid(i,j) == 'F')
                                  color.setBackground(Color.RED);
                             else if (gm.getGrid(i,j) == 'H')
                                  color.setBackground(Color.BLACK);
                             add(color);
              }

    something along these lines
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import javax.swing.*;
    public class MainFrame2
      private static final String EXIT = "Exit";
      private static final String OPEN = "Open...";
      private static final String START = "Start";
      private JPanel mainPanel = new JPanel();
      private JPanel gridPanel = new JPanel();
      public MainFrame2()
        mainPanel.setPreferredSize(new Dimension(300, 300));
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(gridPanel, BorderLayout.CENTER);
      public JComponent getPanel()
        return mainPanel;
      public JMenuBar createMenu()
        JMenu sim = new JMenu("Simulator");
        MenuListener menuListener = new MenuListener();
        JMenuItem m = new JMenuItem(OPEN);
        m.addActionListener(menuListener);
        sim.add(m);
        m = new JMenuItem(START);
        m.addActionListener(menuListener);
        sim.add(m);
        sim.addSeparator();
        m = new JMenuItem(EXIT);
        m.addActionListener(menuListener);
        sim.add(m);
        JMenuBar mBar = new JMenuBar();
        mBar.add(sim);
        return mBar;
      private class MenuListener implements ActionListener
        public void actionPerformed(ActionEvent e)
          String actionCommand = e.getActionCommand();
          if (actionCommand.equals(OPEN))
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Choose a file");
            //mainPanel.add(fileChooser);
            fileChooser.setVisible(true);
            int result = fileChooser.showOpenDialog(mainPanel);
            if (result == JFileChooser.APPROVE_OPTION)
              File file = fileChooser.getSelectedFile();
              GridMap gm = new GridMap();
              gm.read(file);
              int row = gm.getRow();
              int col = gm.getColumn();
              gridPanel.setLayout(new GridLayout(row, col));
              gridPanel.removeAll();
              for (int i = 0; i < row; i++)
                for (int j = 0; j < col; j++)
                  JLabel color = new JLabel();
                  color.setOpaque(true);
                  if (gm.getGrid(i, j) == 'O')
                    color.setBackground(Color.GREEN);
                  else if (gm.getGrid(i, j) == 'F')
                    color.setBackground(Color.RED);
                  else if (gm.getGrid(i, j) == 'H')
                    color.setBackground(Color.BLACK);
                  gridPanel.add(color);
          else if (actionCommand.equals(START))
            // setVisible(true);
          else if (actionCommand.equals(EXIT))
            Window window = SwingUtilities.getWindowAncestor(mainPanel);
            window.dispose();
      private static void createAndShowGUI()
        MainFrame2 frame2 = new MainFrame2();
        JFrame frame = new JFrame("Fire Saving Simulator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(frame2.getPanel());
        frame.setJMenuBar(frame2.createMenu());
        frame.pack();
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        javax.swing.SwingUtilities.invokeLater(new Runnable()
          public void run()
            createAndShowGUI();
    }

  • Problems with JTable custom cell renderers

    Hi All,
    I'm having a bit of a problem writing a custom renderer for a JTable.
    What seems to be happening is that the changes I apply in the renderer to the component are applied to ALL cells.
    All I want to do is have a different background color for certain cells....
    Ive derived from DefaultTableCellRenderer, so Im using its getTableCellRendererComponent to do most of the work.
    So, Ive got something like this:
    private class DirtyCacheRenderer extends DefaultTableCellRenderer
        public Component getTableCellRendererComponent(JTable table, Object value,
                              boolean isSelected, boolean hasFocus, int row, int column)
          // Modifies 'this'
          super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
          // If the row/column is 'dirty' (I.e - if I want 2 color it diferently)
          if(((EditableTableModel)table.getModel()).isDirty(row,column))
            // The column is dirty. Set the color accordingly:
            super.setBackground(DIRTY_COLOR);
          return this;
      }The effect is that as soon as ONE cell gets its color set above, all of the cells do!
    Please help, its driving me mad!!!
    D

    I tried this and it worked. Tell me if it is OK for you.
    import javax.swing.table.TableCellRenderer;
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.JLabel;
    public class testRenderer implements TableCellRenderer {
    JLabel cell = new JLabel();
    Color dirty = new Color(100,100,100);
    Color clear = new Color(0,0,0);
    public testRenderer() {
    cell.setOpaque(true);
    public Component getTableCellRendererComponent(JTable table,Object value,
    boolean isSelected,boolean hasFocus, int row, int column) {
    cell.setText(value.toString());
    // The column is dirty. Set the color
    if (row == column)     {
    cell.setBackground(dirty);
    } else {
    cell.setBackground(table.getBackground());
    return cell;
    }

  • Is it possible to change the default border on a JMenu?

    Hello,
    I'm working on an application that has a simple menu system. Clicking a button opens a JPopupMenu, which contains JMenu and JMenuItem objects. I want to change the border on the JPopupMenu and its JMenu submenus to a simple line border. Calling setBorder on the JPopupMenu works just fine, but calling it on JMenu doesn't change the border. The following code illustrates my point.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MenuTest {
       JFrame f;
       JPanel p;
       JPopupMenu popup;
       JMenu mainMenu;
       JMenu subMenu;
       JButton showPopupButton;
       public MenuTest()
          f = new JFrame("Popup Menu Test");
          p = new JPanel();
          popup = new JPopupMenu();
          subMenu = new JMenu("Submenu");
          mainMenu = new JMenu("Main Menu");
          JMenuItem m;
          for (int i=0; i < 3; i++) {
             m = new JMenuItem("Submenu item " + i);
             subMenu.add(m);
          // This doesn't work.  The border remains set to the default Windows bevel.
          subMenu.setBorder(BorderFactory.createLineBorder(Color.BLACK));
          popup.add(subMenu);
          for (int i=0; i < 5; i++) {
             m = new JMenuItem("Main menu item " + i);
             popup.add(m);
          showPopupButton = new JButton("Show Popup");
          showPopupButton.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e)
                Component c = (Component) e.getSource();
                popup.show(c, 0, c.getHeight());
          p.add(showPopupButton);
          // This works.  It sets the border of the popup menu to a black line border.
          popup.setBorder(BorderFactory.createLineBorder(Color.BLACK));
          f.getContentPane().add(p);
          f.setSize(400, 300);
          f.setVisible(true);
       public static void main(String[] args)
          try {
             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          catch (Exception e) { }
          new MenuTest();
    }Any ideas? Do I have to extend JMenu and do some custom painting to accomplish this? I'd also like to change the roll-over color on the menu items, but neither JMenu nor JPopupMenu seem to support that. It looks like borders and rollover colors are L&F dependent.
    Thanks in advance for any help.

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Example {
        public static void main(String[] args)  throws Exception {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            UIManager.put("MenuItem.selectionForeground", Color.GREEN);
            UIManager.put("MenuItem.selectionBackground", Color.BLACK);
            JMenuBar mb = new JMenuBar();
            Border border = BorderFactory.createRaisedBevelBorder();
            JMenu file = new BorderedMenu("File", border);
            file.add(new JMenuItem("New"));
            file.add(new JMenuItem("Open"));
            file.add(new JMenuItem("Close"));
            JMenu edit = new BorderedMenu("Edit", border);
            edit.add(new JMenuItem("Cut"));
            edit.add(new JMenuItem("Paste"));
            edit.add(new JMenuItem("Copy"));
            mb.add(file);
            mb.add(edit);
            JFrame f = new JFrame("Example");
            f.setJMenuBar(mb);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        static class BorderedMenu extends JMenu {
            private Border border;
            public BorderedMenu(String text, Border border) {
                super(text);
                this.border = border;
            public JPopupMenu getPopupMenu() {
                JPopupMenu p = super.getPopupMenu();
                p.setBorder(border);
                return p;
    }By the way, I find the following program handy when snooping around the UI defaults.
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    public class Listing {
        public static void main(String[] args) throws Exception {
            UIDefaults defs = UIManager.getLookAndFeelDefaults();
            ArrayList list = new ArrayList();
            for(Iterator i = defs.entrySet().iterator(); i.hasNext(); ) {
                Map.Entry entry = (Map.Entry) i.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                if (value instanceof Color)
                    list.add(key);
            Collections.sort(list);
            JPanel panel = new JPanel(new GridLayout(0,1));
            String lastCompName = "";
            for(int i=0; i<list.size(); ++i) {
                Object key = list.get(i);
                String text = key.toString();
                int dotIndex = text.indexOf('.');
                String compName = text.substring(0, dotIndex > 0 ? dotIndex : text.length());
                if (!compName.equals(lastCompName)) {
                    lastCompName = compName;
                    panel.add(new JLabel());
                Color color = defs.getColor(key);
                JLabel label = new JLabel(text, new ColorIcon(color), JLabel.LEFT);
                panel.add(label);
            JFrame f = new JFrame("Listing");
            f.getContentPane().add(new JScrollPane(panel));
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.pack();
            f.setSize(f.getWidth(), 600);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class ColorIcon implements Icon {
        public static final int ICON_WIDTH = 20;
        public static final int ICON_HEIGHT = 16;
        private Color color;
        public ColorIcon(Color color) {
            this.color = color;
        public int getIconWidth() {
            return ICON_WIDTH;
        public int getIconHeight() {
            return ICON_HEIGHT;
        public void paintIcon(Component c, Graphics g, int x, int y) {
            if (color != null) {
                Color old = g.getColor();
                g.setColor(color);
                g.fillRect(x, y, ICON_WIDTH, ICON_HEIGHT);
                g.setColor(Color.BLACK);
                g.drawRect(x, y, ICON_WIDTH-1, ICON_HEIGHT-1);
                g.setColor(old);
    }

  • Need help getting Main method to work...

    Hello everyone, I have a problem, I have a GUI that I need to run (it compiles fine, but will not run.) I am very new to Java and programing in general so go easy on me. I think I am just missing something simple here. I am going to post the basic code and see if you all can help...the issue is in written in red to help you identify my problem...
    public class LagersGUI extends JFrame implements ActionListener,Serializable
    {color:#0000ff}private {color}JTextArea {color:#339966}textArea{color};
    {color:#0000ff}private {color}JButton {color:#339966}start,
    next,
    previous,
    last;{color}
    JLabel {color:#339966}imageLabel{color};
    {color:#0000ff}private static{color} LagersAddInfo {color:#339966}inv{color} = {color:#0000ff}new {color}LagersAddInfo();
    {color:#808080} /**
    * @param arg0
    * @throws HeadlessException
    */{color}
    {color:#0000ff}public {color}LagersGUI( String arg0 ) {color:#0000ff}throws {color}HeadlessException
    {color:#0000ff}super{color}( {color:#ff9900}"Inventory GUI" {color});
    {color:#339966}textArea{color} = {color:#0000ff}new {color}JTextArea( 800,800 );
    JScrollPane scrollPane = new JScrollPane( {color:#339966}textArea{color} );
    textArea.setEditable( {color:#0000ff}false {color});
    scrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
    scrollPane.setPreferredSize( new Dimension( 600, 100 ) );
    JPanel cp = new JPanel();
    cp.setSize( 400, 100 );
    cp.setLayout( new BorderLayout() );
    cp.add( scrollPane,BorderLayout.{color:#339966}CENTER{color} );
    JPanel buttonPanel = new JPanel();
    JPanel buttonPanel1 = new JPanel();
    {color:#339966}start{color} = new JButton( {color:#ff9900}"Start"{color} );
    {color:#339966}start{color}.addActionListener( {color:#0000ff}this {color});
    {color:#339966} next{color} = new JButton( {color:#ff9900}"Next" {color});
    {color:#339966} next{color}.addActionListener( {color:#0000ff}this {color});
    {color:#339966}previous{color} = new JButton( {color:#ff9900}"Previous"{color} );
    {color:#339966} previous{color}.addActionListener( {color:#0000ff}this {color});
    {color:#339966} last{color} = new JButton({color:#ff9900} "Last"{color} );
    {color:#339966} last{color}.addActionListener( {color:#0000ff}this {color});
    buttonPanel.add( {color:#339966}start {color});
    buttonPanel.add( {color:#339966}next {color});
    buttonPanel.add( {color:#339966}previous {color});
    buttonPanel.add( {color:#339966}last {color});
    cp.add( buttonPanel,BorderLayout.{color:#339966}SOUTH {color});
    cp.add( buttonPanel1,BorderLayout.{color:#339966}NORTH {color});{color:#999999}///NewInventory_Test/logo.gif{color}
    java.net.URL u = {color:#0000ff}this{color}.getClass().getClassLoader().getResource({color:#ff9900}"\\NewInventory_Test\\logo.gif"{color});
    ImageIcon icon = {color:#0000ff}new {color}ImageIcon(u);
    {color:#339966}imageLabel{color} = new JLabel( {color:#ff9900}"Inventory View"{color}, icon, JLabel.{color:#339966}CENTER {color});
    cp.add({color:#339966} imageLabel{color},BorderLayout.{color:#339966}WEST{color} );
    {color:#0000ff}this{color}.setContentPane( cp );
    {color:#0000ff}this{color}.setContentPane( cp );
    {color:#0000ff}this{color}.setTitle( "Inventory Program IT 215" );
    {color:#0000ff}this{color}.setDefaultCloseOperation( JFrame.{color:#339966}EXIT_ON_CLOSE{color} );
    {color:#0000ff} this{color}.{color:#339966}textArea{color}.setText({color:#339966}inv{color}.getStart());
    {color:#0000ff} this{color}.setSize(200, 200);
    {color:#0000ff}this{color}.pack();
    {color:#0000ff}this{color}.setVisible( {color:#0000ff}true {color});
    @Override
    {color:#0000ff}public void{color} actionPerformed( ActionEvent e )
    // TODO Auto-generated method stub
    {color:#0000ff} if {color}( e.getActionCommand().equals({color:#ff9900} "Start"{color} ) )
    textArea.setText( {color:#339966}inv{color}.getStart() );
    {color:#0000ff}if {color}( e.getActionCommand().equals( {color:#ff9900}"Next" {color}) )
    textArea.setText({color:#339966}inv{color}.getNext());
    {color:#0000ff}if{color} ( e.getActionCommand().equals( {color:#ff9900}"Previous" {color}) )
    textArea.setText( {color:#339966}inv{color}.getPrevious() );
    {color:#0000ff} if{color} ( e.getActionCommand().equals( {color:#ff9900}"Last"{color} ) )
    textArea.setText({color:#339966}inv{color}.getLast());
    {color:#0000ff}public static {color}LagersAddInfo getInv()
    {color:#0000ff}return{color:#339966} {color}{color}{color:#339966}inv{color};
    {color:#0000ff}public static void{color} setInv( LagersAddInfo inv )
    LagersGUI.{color:#339966}inv {color}= inv;
    {color:#808080} /**
    * @param args
    */{color}
    {color:#0000ff}public static void {color}main( String[] args )
    LagersGUI {color:#ff0000}_inventory_ {color}= {color:#0000ff}new {color}LagersGUI( {color:#ff9900}"Inventory"{color} );{color:#ff0000}//** here's the part I'm having trouble with...inventory is an * unused variable. What other way could I get {color:#000000}main{color} */ method to work?{color}
    }

    This forum can format your code for you and make it easier to read. Simply click the CODE button and two tags will appear. Then paste your code in between the tags. Important, copy code form your source not first post.                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Can U help me change "Paint.java" to MVC model

    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollBar;
    import javax.swing.JTextField;
    import javax.swing.ImageIcon;
    public class Paint extends Applet implements ActionListener, AdjustmentListener, MouseListener, MouseMotionListener
    private static final long serialVersionUID = 1L;
    private final int NO_OP = 0;
    private final int PEN_OP = 1;
    private final int LINE_OP = 2;
    private final int ERASER_OP = 3;
    private final int CLEAR_OP = 4;
    private final int RECT_OP = 5;
    private final int OVAL_OP = 6;
    private final int FRECT_OP = 7;
    private final int FOVAL_OP = 8;
    private final int SPLINE_OP = 9;
    private final int POLY_OP = 10;
    private int mousex = 0;
    private int mousey = 0;
    private int prevx = 0;
    private int prevy = 0;
    private boolean initialPen = true;
    private boolean initialLine = true;
    private boolean initialEraser = true;
    private boolean initialRect = true;
    private boolean initialOval = true;
    private boolean initialFRect = true;
    private boolean initialFOval = true;
    private boolean initialPolygon = true;
    private boolean initialSpline = true;
    private int Orx = 0;
    private int Ory = 0;
    private int OrWidth = 0;
    private int OrHeight = 0;
    private int drawX = 0;
    private int drawY = 0;
    private int eraserLength = 5;
    private int udefRedValue = 255;
    private int udefGreenValue = 255;
    private int udefBlueValue = 255;
    private int opStatus = PEN_OP;
    private int colorStatus = 1;
    private Color mainColor = new Color(0,0,0);
    private Color xorColor = new Color(255,255,255);
    private Color statusBarColor = new Color(166,166,255);
    private Color userDefinedColor = new Color(udefRedValue,udefGreenValue,udefBlueValue);
    private JButton penButton           = new JButton(new ImageIcon(getClass().getResource("pen.gif")));
    private JButton lineButton           = new JButton(new ImageIcon(getClass().getResource("line.gif")));
    private JButton eraserButton           = new JButton(new ImageIcon(getClass().getResource("eraser.gif")));
    private JButton clearButton = new JButton("Clear");
    private JButton rectButton           = new JButton(new ImageIcon(getClass().getResource("rec.gif")));
    private JButton ovalButton           = new JButton(new ImageIcon(getClass().getResource("oval.gif")));
    private JButton fillRectButton      = new JButton(new ImageIcon(getClass().getResource("fillrec.gif")));
    private JButton fillOvalButton      = new JButton(new ImageIcon(getClass().getResource("filloval.gif")));
    private JButton splineButton = new JButton("Spline");
    private JButton polygonButton = new JButton("Polygon");
    private JButton blackButton = new JButton("Black");
    private JButton blueButton = new JButton("Blue");
    private JButton redButton = new JButton("Red");
    private JButton greenButton = new JButton("Green");
    private JButton purpleButton = new JButton("Purple");
    private JButton orangeButton = new JButton("Orange");
    private JButton pinkButton = new JButton("Pink");
    private JButton grayButton = new JButton("Gray");
    private JButton yellowButton = new JButton("Yellow");
    private JButton userDefButton = new JButton("User-Def");
    private JScrollBar redSlider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 1, 0, 255);
    private JScrollBar blueSlider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 1, 0, 255);
    private JScrollBar greenSlider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 1, 0, 255);
    private JTextField colorStatusBar = new JTextField(20);
    private JTextField opStatusBar = new JTextField(20);
    private JTextField mouseStatusBar = new JTextField(10);
    private JTextField redValue = new JTextField(3);
    private JTextField greenValue = new JTextField(3);
    private JTextField blueValue = new JTextField(3);
    private JLabel operationLabel = new JLabel(" Tool mode:");
    private JLabel colorLabel = new JLabel(" Color mode:");
    private JLabel cursorLabel = new JLabel(" Cursor:");
    private JPanel ToolbarPanel = new JPanel(new GridLayout(11,2,0,0));
    private JPanel drawPanel = new JPanel();
    private JPanel statusPanel = new JPanel();
    private JPanel udefcolPanel = new JPanel(new GridLayout(3,3,0,0));
    private JPanel udefdemcolPanel = new JPanel();
    private JPanel PicPanel               = new JPanel();
    public void init()
    setLayout(new BorderLayout());
    ToolbarPanel.add(blackButton);
    ToolbarPanel.add(blueButton);
    ToolbarPanel.add(redButton);
    ToolbarPanel.add(greenButton);
    ToolbarPanel.add(purpleButton);
    ToolbarPanel.add(orangeButton);
    ToolbarPanel.add(pinkButton);
    ToolbarPanel.add(grayButton);
    ToolbarPanel.add(yellowButton);
    ToolbarPanel.add(userDefButton);
    blueButton.setBackground(Color.blue);
    redButton.setBackground(Color.red);
    greenButton.setBackground(Color.green);
    purpleButton.setBackground(Color.magenta);
    orangeButton.setBackground(Color.orange);
    pinkButton.setBackground(Color.pink);
    grayButton.setBackground(Color.gray);
    yellowButton.setBackground(Color.yellow);
    userDefButton.setBackground(userDefinedColor);
    ToolbarPanel.add(penButton);
    ToolbarPanel.add(lineButton);
    ToolbarPanel.add(eraserButton);
    ToolbarPanel.add(clearButton);
    ToolbarPanel.add(rectButton);
    ToolbarPanel.add(ovalButton);
    ToolbarPanel.add(fillRectButton);
    ToolbarPanel.add(fillOvalButton);
    ToolbarPanel.add(splineButton);
    ToolbarPanel.add(polygonButton);
    ToolbarPanel.setBounds(0,0,100,300);
    ToolbarPanel.add(udefcolPanel);
    ToolbarPanel.add(udefdemcolPanel);
    udefcolPanel.add(redValue);
    udefcolPanel.add(redSlider);
    udefcolPanel.add(greenValue);
    udefcolPanel.add(greenSlider);
    udefcolPanel.add(blueValue);
    udefcolPanel.add(blueSlider);
    statusPanel.add(colorLabel);
    statusPanel.add(colorStatusBar);
    statusPanel.add(operationLabel);
    statusPanel.add(opStatusBar);
    statusPanel.add(cursorLabel);
    statusPanel.add(mouseStatusBar);
    colorStatusBar.setEditable(false);
    opStatusBar.setEditable(false);
    mouseStatusBar.setEditable(false);
    statusPanel.setBackground(statusBarColor);
    ToolbarPanel.setBackground(Color.white);
    drawPanel.setBackground(Color.white);
    add(statusPanel, "North");
    add(ToolbarPanel, "West");
    add(drawPanel, "Center");
    penButton.addActionListener(this);
    lineButton.addActionListener(this);
    eraserButton.addActionListener(this);
    clearButton.addActionListener(this);
    rectButton.addActionListener(this);
    ovalButton.addActionListener(this);
    fillRectButton.addActionListener(this);
    fillOvalButton.addActionListener(this);
    splineButton.addActionListener(this);
    polygonButton.addActionListener(this);
    blackButton.addActionListener(this);
    blueButton.addActionListener(this);
    redButton.addActionListener(this);
    greenButton.addActionListener(this);
    purpleButton.addActionListener(this);
    orangeButton.addActionListener(this);
    pinkButton.addActionListener(this);
    grayButton.addActionListener(this);
    yellowButton.addActionListener(this);
    userDefButton.addActionListener(this);
    redSlider.addAdjustmentListener(this);
    blueSlider.addAdjustmentListener(this);
    greenSlider.addAdjustmentListener(this);
    drawPanel.addMouseMotionListener(this);
    drawPanel.addMouseListener(this);
    // this.addMouseListener(this);
    // this.addMouseMotionListener(this);
    updateRGBValues();
    opStatusBar.setText("Pen");
    colorStatusBar.setText("Black");
    public void actionPerformed(ActionEvent e)
         penButton.setActionCommand("Pen");
         lineButton.setActionCommand("Line");
         eraserButton.setActionCommand("Eraser");
         rectButton.setActionCommand("Rectangle");
         ovalButton.setActionCommand("Oval");
         fillRectButton.setActionCommand("Filled Rectangle");
         fillOvalButton.setActionCommand("Filled Oval");
         if (e.getActionCommand() == "Pen")
         opStatus = PEN_OP;
         else if (e.getActionCommand() == "Line")
         opStatus = LINE_OP;
         else if (e.getActionCommand() == "Eraser")
         opStatus = ERASER_OP;
         else if (e.getActionCommand() == "Clear")
         opStatus = CLEAR_OP;
         else if (e.getActionCommand() == "Rectangle")
         opStatus = RECT_OP;
         else if (e.getActionCommand() == "Oval")
         opStatus = OVAL_OP;
         else if (e.getActionCommand() == "Filled Rectangle")
         opStatus = FRECT_OP;
         else if (e.getActionCommand() == "Filled Oval")
         opStatus = FOVAL_OP;
         else if (e.getActionCommand() == "Polygon")
         opStatus = POLY_OP;
         else if (e.getActionCommand() == "Spline")
         opStatus = SPLINE_OP;
         else if (e.getActionCommand() == "Black")
         colorStatus = 1;
         else if (e.getActionCommand() == "Blue")
         colorStatus = 2;
         else if (e.getActionCommand() == "Green")
         colorStatus = 3;
         else if (e.getActionCommand() == "Red")
         colorStatus = 4;
         else if (e.getActionCommand() == "Purple")
         colorStatus = 5;
         else if (e.getActionCommand() == "Orange")
         colorStatus = 6;
         else if (e.getActionCommand() == "Pink")
         colorStatus = 7;
         else if (e.getActionCommand() == "Gray")
         colorStatus = 8;
         else if (e.getActionCommand() == "Yellow")
         colorStatus = 9;
         else if (e.getActionCommand() == "User-Def")
         colorStatus = 10;
    initialPolygon = true;
    initialSpline = true;
    switch (opStatus)
    case PEN_OP : opStatusBar.setText("Pen");
    break;
    case LINE_OP : opStatusBar.setText("Line");
    break;
    case ERASER_OP: opStatusBar.setText("Eraser");
    break;
    case CLEAR_OP : clearPanel(drawPanel);
    break;
    case RECT_OP : opStatusBar.setText("Rectangle");
    break;
    case OVAL_OP : opStatusBar.setText("Oval");
    break;
    case FRECT_OP : opStatusBar.setText("Fill-Rectangle");
    break;
    case FOVAL_OP : opStatusBar.setText("Fill-Oval");
    break;
    case POLY_OP : opStatusBar.setText("Polygon");
    break;
    case SPLINE_OP: opStatusBar.setText("Spline");
    break;
    switch (colorStatus)
    case 1: colorStatusBar.setText("Black");
    break;
    case 2: colorStatusBar.setText("Blue");
    break;
    case 3: colorStatusBar.setText("Green");
    break;
    case 4: colorStatusBar.setText("Red");
    break;
    case 5: colorStatusBar.setText("Purple");
    break;
    case 6: colorStatusBar.setText("Orange");
    break;
    case 7: colorStatusBar.setText("Pink");
    break;
    case 8: colorStatusBar.setText("Gray");
    break;
    case 9: colorStatusBar.setText("Yellow");
    break;
    case 10: colorStatusBar.setText("User Defined Color");
    break;
    setMainColor();
    updateRGBValues();
    public void adjustmentValueChanged(AdjustmentEvent e)
    updateRGBValues();
    public void clearPanel(JPanel drawPanel2)
    opStatusBar.setText("Clear");
    Graphics g = drawPanel2.getGraphics();
    g.setColor(drawPanel2.getBackground());
    g.fillRect(0,0,drawPanel2.getBounds().width,drawPanel2.getBounds().height);
    public void penOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialPen)
    setGraphicalDefaults(e);
    initialPen = false;
    g.drawLine(prevx,prevy,mousex,mousey);
    if (mouseHasMoved(e))
    mousex = e.getX();
    mousey = e.getY();
    g.drawLine(prevx,prevy,mousex,mousey);
    prevx = mousex;
    prevy = mousey;
    public void lineOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialLine)
    setGraphicalDefaults(e);
    g.setXORMode(xorColor);
    g.drawLine(Orx,Ory,mousex,mousey);
    initialLine=false;
    if (mouseHasMoved(e))
    g.setXORMode(xorColor);
    g.drawLine(Orx,Ory,mousex,mousey);
    mousex = e.getX();
    mousey = e.getY();
    g.drawLine(Orx,Ory,mousex,mousey);
    public void rectOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialRect)
    setGraphicalDefaults(e);
    initialRect = false;
    if (mouseHasMoved(e))
    g.setXORMode(drawPanel.getBackground());
    g.drawRect(drawX,drawY,OrWidth,OrHeight);
    mousex = e.getX();
    mousey = e.getY();
    setActualBoundry();
    g.drawRect(drawX,drawY,OrWidth,OrHeight);
    public void ovalOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialOval)
    setGraphicalDefaults(e);
    initialOval=false;
    if (mouseHasMoved(e))
    g.setXORMode(xorColor);
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    mousex = e.getX();
    mousey = e.getY();
    setActualBoundry();
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    public void frectOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialFRect)
    setGraphicalDefaults(e);
    initialFRect=false;
    if (mouseHasMoved(e))
    g.setXORMode(xorColor);
    g.drawRect(drawX,drawY,OrWidth-1,OrHeight-1);
    mousex = e.getX();
    mousey = e.getY();
    setActualBoundry();
    g.drawRect(drawX,drawY,OrWidth-1,OrHeight-1);
    public void fovalOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialFOval)
    setGraphicalDefaults(e);
    initialFOval = false;
    if (mouseHasMoved(e))
    g.setXORMode(xorColor);
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    mousex = e.getX();
    mousey = e.getY();
    setActualBoundry();
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    public void eraserOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    if (initialEraser)
    setGraphicalDefaults(e);
    initialEraser = false;
    g.setColor(mainColor.white);
    g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
    g.setColor(Color.black);
    g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
    prevx = mousex;
    prevy = mousey;
    if (mouseHasMoved(e))
    g.setColor(mainColor.white);
    g.drawRect(prevx-eraserLength, prevy-eraserLength,eraserLength*2,eraserLength*2);
    mousex = e.getX();
    mousey = e.getY();
    g.setColor(mainColor.white);
    g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
    g.setColor(Color.black);
    g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
    prevx = mousex;
    prevy = mousey;
    public void polygonOperation(MouseEvent e)
    if (initialPolygon)
    prevx = e.getX();
    prevy = e.getY();
    initialPolygon = false;
    else
    mousex = e.getX();
    mousey = e.getY();
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.drawLine(prevx,prevy,mousex,mousey);
    prevx = mousex;
    prevy = mousey;
    public void splineOperation(MouseEvent e)
    if(initialSpline)
    initialSpline = false;
    public boolean mouseHasMoved(MouseEvent e)
    return (mousex != e.getX() || mousey != e.getY());
    public void setActualBoundry()
    if (mousex < Orx || mousey < Ory)
    if (mousex < Orx)
    OrWidth = Orx - mousex;
    drawX = Orx - OrWidth;
    else
    drawX = Orx;
    OrWidth = mousex - Orx;
    if (mousey < Ory)
    OrHeight = Ory - mousey;
    drawY = Ory - OrHeight;
    else
    drawY = Ory;
    OrHeight = mousey - Ory;
    else
    drawX = Orx;
    drawY = Ory;
    OrWidth = mousex - Orx;
    OrHeight = mousey - Ory;
    public void setGraphicalDefaults(MouseEvent e)
    mousex = e.getX();
    mousey = e.getY();
    prevx = e.getX();
    prevy = e.getY();
    Orx = e.getX();
    Ory = e.getY();
    drawX = e.getX();
    drawY = e.getY();
    OrWidth = 0;
    OrHeight = 0;
    public void mouseDragged(MouseEvent e)
    updateMouseCoordinates(e);
    switch (opStatus)
    case PEN_OP : penOperation(e);
    break;
    case LINE_OP : lineOperation(e);
    break;
    case RECT_OP : rectOperation(e);
    break;
    case OVAL_OP : ovalOperation(e);
    break;
    case FRECT_OP : frectOperation(e);
    break;
    case FOVAL_OP : fovalOperation(e);
    break;
    case ERASER_OP: eraserOperation(e);
    break;
    public void mouseReleased(MouseEvent e)
    updateMouseCoordinates(e);
    switch (opStatus)
    case PEN_OP : releasedPen();
    break;
    case LINE_OP : releasedLine();
    break;
    case RECT_OP : releasedRect();
    break;
    case OVAL_OP : releasedOval();
    break;
    case FRECT_OP : releasedFRect();
    break;
    case FOVAL_OP : releasedFOval();
    break;
    case ERASER_OP : releasedEraser();
    break;
    public void mouseEntered(MouseEvent e)
    updateMouseCoordinates(e);
    public void setMainColor()
    switch (colorStatus)
    case 1 : mainColor = Color.black;
    break;
    case 2: mainColor = Color.blue;
    break;
    case 3: mainColor = Color.green;
    break;
    case 4: mainColor = Color.red;
    break;
    case 5: mainColor = Color.magenta;
    break;
    case 6: mainColor = Color.orange;
    break;
    case 7: mainColor = Color.pink;
    break;
    case 8: mainColor = Color.gray;
    break;
    case 9: mainColor = Color.yellow;
    break;
    case 10: mainColor = userDefinedColor;
    break;
    public void releasedPen()
    initialPen = true;
    public void releasedLine()
    if ((Math.abs(Orx-mousex)+Math.abs(Ory-mousey)) != 0)
    // System.out.println("Line has been released....");
    initialLine = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.drawLine(Orx,Ory,mousex,mousey);
    public void releasedEraser()
    initialEraser = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor.white);
    g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
    public void releasedRect()
    initialRect = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.drawRect(drawX,drawY,OrWidth,OrHeight);
    public void releasedOval()
    initialOval = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    public void releasedFRect()
    initialFRect = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.fillRect(drawX,drawY,OrWidth,OrHeight);
    public void releasedFOval()
    initialFOval = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.fillOval(drawX,drawY,OrWidth,OrHeight);
    public void updateMouseCoordinates(MouseEvent e)
    String xCoor ="";
    String yCoor ="";
    if (e.getX() < 0) xCoor = "0";
    else
    xCoor = String.valueOf(e.getX());
    if (e.getY() < 0) xCoor = "0";
    else
    yCoor = String.valueOf(e.getY());
    mouseStatusBar.setText("x:"+xCoor+" y:"+yCoor);
    public void updateRGBValues()
    udefRedValue = redSlider.getValue();
    udefGreenValue = greenSlider.getValue();
    udefBlueValue = blueSlider.getValue();
    if (udefRedValue > 255)
    udefRedValue = 255;
    if (udefRedValue < 0 )
    udefRedValue =0;
    if (udefGreenValue > 255)
    udefGreenValue = 255;
    if (udefGreenValue < 0 )
    udefGreenValue =0;
    if (udefBlueValue > 255)
    udefBlueValue = 255;
    if (udefBlueValue < 0 )
    udefBlueValue =0;
    redValue.setText(String.valueOf(udefRedValue));
    greenValue.setText(String.valueOf(udefGreenValue));
    blueValue.setText(String.valueOf(udefBlueValue));
    userDefinedColor = new Color(udefRedValue,udefGreenValue,udefBlueValue);
    userDefButton.setBackground(userDefinedColor);
    Graphics g = udefdemcolPanel.getGraphics();
    g.setColor(userDefinedColor);
    g.fillRect(0,0,800,800);
    public void mouseClicked(MouseEvent e)
    updateMouseCoordinates(e);
    switch (opStatus)
    case 9 : splineOperation(e);
    break;
    case 10 : polygonOperation(e);
    break;
    public void mouseExited(MouseEvent e)
    updateMouseCoordinates(e);
    public void mouseMoved(MouseEvent e)
    updateMouseCoordinates(e);
    public void mousePressed(MouseEvent e)
    updateMouseCoordinates(e);
    Edited by: eclipse on Feb 19, 2008 6:29 AM

    If you can't divide the class then you can't implement an MVC design methodology.
    This class is a giant mess and can be EASILY broken down into smaller classes. Seperate the visual components into their own classes. Create Model objects that contain the data behind your visual components.
    Split up your giant ActionListener into several smaller more specialized actionlisteners and create a Controller object that you can assign these listeners and models to. Allow the event handling to be done by the controller so it can propogate necessary data changes to the models, thus altering the Views.
    Thats it in a nutshell. It is not an easy answer.

Maybe you are looking for

  • Base Value not changing in MIGO Excise Tab

    Dear Gururs, We are using MIGO to capture & Post Excise Invoice for our Import PO (PO type ZIMP). the problem is, when we change the qty in MIGO Qty tab, corresponding base value is not getting update in Excise tab. Please suggest a solution.

  • MSI P6N Diamond 680i and G0 stepping?

    Does this board support G0 stepping right now? No bios updated needed? I've heard some boards do not. I'm looking at getting one of the new Q6600's w/ G0 stepping.

  • G/l account is not appearing in purchase requisition

    Hi Folks, I have created PR via CRM FSO. The PR itself does not have the GL Account in the Account Assignment tab and so the PR does not show as a commitment in KO03 or KOB2.why the pr is not picking the g/l account. please help me out. Regards, Nara

  • Why is the service in our building so bad?

    Recently the Verizon Wireless service in our building has become absolutely awful.  We have clients walking up to the windows and holding up their phones trying to get a decent signal.  Calls drop all the time and our phones almost always say 1x.  Th

  • OS 4.0.1 Update

    Is there some reason why software updates have such an issue updating on Windows XP, because every time i try to update my dad's phone it has issues? Or does having a lot of security software on your laptop affect the process? I always end up having