Why I cannot Move my JLabel after I add SetToolTipText()??


Dear Friends:
I met a tough problem that I debugged for few days but cannot solve it.
after I add SetToolTipText I cannot Move my JLabel , what is wrong here\t
see code below, here label1 cannot move.
If somebody can throw some lights, that will be wonderful,
so far no progress.

import java.awt.*; import java.awt.event.*; import java.util.Vector; import javax.swing.*; import javax.swing.border.LineBorder; import javax.swing.event.*; public class DNDJLabels extends JPanel { protected JLabel label1, label2, label3, label4; protected JLabel[] labels; protected JLabel selectedLabel; LineBorder black = new LineBorder(Color.black, 3, false); int cx, cy; protected Vector order = new Vector(); public static void main(String[] args) { JFrame f = new JFrame("Connecting Lines"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(new DNDJLabels()); f.setSize(600,700); f.setLocation(200,200); f.setVisible(true); } public DNDJLabels () { setLayout(null); addLabels(); label1.setBounds( 125, 150, 150, 60); label2.setBounds(425, 150, 150, 60); label3.setBounds( 125, 575, 150, 60); label4.setBounds(425, 575, 150, 60); label1.setBorder(black); label2.setBorder(black); label3.setBorder(black); label4.setBorder(black); //add(btn); label1.setToolTipText("AAAAAAAA"); determineCenterOfComponents(); ComponentMover mover = new ComponentMover(); addMouseListener(mover); addMouseMotionListener(mover); } public void paintComponent(final Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); Point[] p; g2.setStroke(new BasicStroke(4f)); for(int i = 0 ; i < order.size()-1; i++) { JLabel l1 = (JLabel)order.elementAt(i); JLabel l2 = (JLabel)order.elementAt(i+1); p = getCenterPoints(l1, l2); g2.setColor(Color.black); //g2.draw(new Line2D.Double(p[0], p[1])); } } private Point[] getCenterPoints(Component c1, Component c2) { Point p1 = new Point(), p2 = new Point(); Rectangle r1 = c1.getBounds(), r2 = c2.getBounds(); p1.x = r1.x + r1.width/2; p1.y = r1.y + r1.height/2; p2.x = r2.x + r2.width/2; p2.y = r2.y + r2.height/2; return new Point[] {p1, p2}; } private void determineCenterOfComponents() { int xMin = Integer.MAX_VALUE, yMin = Integer.MAX_VALUE, xMax = 0, yMax = 0; for(int i = 0; i < labels.length; i++) { Rectangle r = labels[i].getBounds(); if(r.x < xMin) xMin = r.x; if(r.y < yMin) yMin = r.y; if(r.x + r.width > xMax) xMax = r.x + r.width; if(r.y + r.height > yMax) yMax = r.y + r.height; } cx = xMin + (xMax - xMin)/2; cy = yMin + (yMax - yMin)/2; } private class ComponentMover extends MouseInputAdapter { Point offsetP = new Point(); boolean dragging; public void mousePressed(MouseEvent e) { Point p = e.getPoint(); for(int i = 0; i < labels.length; i++) { Rectangle r = labels[i].getBounds(); if(r.contains(p)) { selectedLabel = labels[i]; order.addElement(labels[i]); offsetP.x = p.x - r.x; offsetP.y = p.y - r.y; dragging = true; repaint(); //added break; } } } public void mouseReleased(MouseEvent e) { } public void mouseDragged(MouseEvent e) { Rectangle r = selectedLabel.getBounds(); r.x = e.getX() - offsetP.x; r.y = e.getY() - offsetP.y; selectedLabel.setBounds(r.x, r.y, r.width, r.height); //determineCenterOfComponents(); repaint(); } } private void addLabels() { label1 = new JLabel("Label 1"); label2 = new JLabel("Label 2"); label3 = new JLabel("Label 3"); label4 = new JLabel("Label 4"); labels = new JLabel[] { label1, label2, label3, label4 }; //add(btn); for(int i = 0; i < labels.length; i++) { labels[i].setHorizontalAlignment(SwingConstants.CENTER); labels[i].setBorder(BorderFactory.createEtchedBorder()); add(labels[i]); } } }
Posted On: Monday 22nd of October 2012 04:13:32 AM Total Views:  85
View Complete with Replies

RELATED TOPICS OF Swing / AWT / SWT PROGRAMMING LANGUAGE




java.lang.ClassCastException: javax.swing.KeyStroke cannot be cast to java.lang.Comparable

The SWING frame work that i am using is working fine with jre1.6.When i try to run it through jre1.7 getting the below exception . java.lang.ClassCastException: javax.swing.KeyStroke cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(Unknown Source) at java.util.TreeMap.put(Unknown Source) at java.util.TreeSet.add(Unknown Source) Can any one help to reslove this ..
VIEWS ON THIS POST

160

Posted on:

Saturday 22nd September 2012
View Replies!

problem in movement logic

Sorry if i am posting this in wrong thread. import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.ImageObserver; import javax.swing.JLabel; class Cfish{ int x = 0; int y = 0; int dx = 2; int dy = 1; Image fishImg; int direction =1; public Cfish() {} public Cfish(int x, int y, Image img) { fishImg = img; this.x = x; this.y = y; } public void movementFish(Cpoint sp) { if(x+dx>sp.getWidth()) { x = sp.getWidth(); dx = -dx; direction *= -1; } else if(x+dxsp.getHeight()) { y = sp.getHeight(); dy = -dy; } else if(y+dy
VIEWS ON THIS POST

115

Posted on:

Wednesday 26th September 2012
View Replies!

jtabbedpane is a pain in the butt; how do I place labels and move them around?

I am pretty new to Eclipse windows builder and Java and I created these tabs with Labels and buttons, but I am not able to move them around Anyone know why not If I put a label in a jframe, and I select absolute coordinates, I am able to move them as I wish, but not when I put them in in a tabbed pane Also wheneever I add another label or button, it creates another pane! public class appWindow { private JFrame frame; private JLabel lblLabel2; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { appWindow window = new appWindow(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public appWindow() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 798, 670); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new GridLayout(0, 1, 0, 0)); JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); JLabel lblLabel1 = new JLabel("Label1"); tabbedPane.addTab("New tab", null, lblLabel1, null); lblLabel2 = new JLabel("LABEL2"); tabbedPane.addTab("New tab", null, lblLabel2, null); frame.getContentPane().add(tabbedPane); JButton btnButton = new JButton("button1"); tabbedPane.addTab("New tab", null, btnButton, null); } }
VIEWS ON THIS POST

75

Posted on:

Wednesday 26th September 2012
View Replies!

I cannot for the *life* of me set the focus to my desired window.

I've been at this for hours. I've now distilled it down to a very simple test program. First, I'm running JRE 7 on Linux (I've heard that can make a difference). Here is what I'd like the following program to do: 1. Open 3 windows 2. Set the focus to "TestWindow 1" What it actually does: 1. Opens 3 windows 2. Sets the focus typically to "TestWindow 3" and sometimes to "TestWindow 2" After much reading, I've moved the focus request (and almost everything else gui related for that matter) into the event dispatch thread. Please let me know your ideas! Now I'm dying of curiosity as to the solution. Class TestWindow import javax.swing.*; public class TestWindow { JFrame jFrame; TestWindow(String name, int x, int y) { DefaultListModel defaultListModel = new DefaultListModel(); defaultListModel.addElement("one"); defaultListModel.addElement("two"); defaultListModel.addElement("three"); JList jList = new JList(defaultListModel); JPanel jPanel = new JPanel(); jPanel.add(jList); jFrame = new JFrame(); jFrame.add(jPanel); jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jFrame.setTitle(name); jFrame.setSize(200, 100); jFrame.setLocation(x,y); jFrame.setVisible(true); } public JFrame getJFrame(){ return jFrame; } }
VIEWS ON THIS POST

132

Posted on:

Wednesday 26th September 2012
View Replies!

need help to move a ball from scratch

Can anyone please help me to move a ball step by step, i found lots of codes on internet for moving ball, but i want to understand it step by step... initially i created two classes that displaying a ball on window... Cball.java import javax.swing.*; public class Cball { public static void main(String args[]) { JFrame frame = new JFrame(); frame.setVisible(true); frame.setSize(500,300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Cpoint point = new Cpoint(); frame.add(point); point.drawing(); } }
VIEWS ON THIS POST

109

Posted on:

Wednesday 3rd October 2012
View Replies!

real time movement for container

everybody. I am building a gui within an applet, which does have an animation and updates frequently. Therefore to prevent redrawing overlaying UI components of the animating component, i have set up a few JDialogs. These need to become relocated as the "main frame" gets moved/dragged. In order to deal with that, i have registered a componentlistener to the owner frame of the applet. Unfortunately it feels like the componentMoved event does not get called realtime. Therefore as i do move the main frame, the dialogs are moving a little bit slower, which just looks ugly. I was wondering, if there is any possibility to register/override mouseDragged of the Titilebar and extend it by my location update. It just seems that componentMoved is slightly to slow. Here is some code: @Override public void componentMoved(ComponentEvent e) { relocateDialogs(); private void relocateDialogs() { settingsParent.setLocation(getLocationOnScreen().x + getWidth() - settings.getWidth(), getLocationOnScreen().y + headerSize + offsetSettings); optionsParent.setLocation(getLocationOnScreen().x + getWidth() - options.getWidth(), getLocationOnScreen().y + headerSize + offsetOptions); legendParent.setLocation(getLocationOnScreen().x + getWidth() - legend.getWidth(), getLocationOnScreen().y + headerSize + offsetLegend); }
VIEWS ON THIS POST

141

Posted on:

Tuesday 16th October 2012
View Replies!

jtextpane.setText() removes \n

whenever i place in properly formatted html code with \n in them, they get removed when jtextpane.setText() gets called. the document.putproperty() end of line string does not work either anyone encountered this problem would like to hear your thoughts
VIEWS ON THIS POST

105

Posted on:

Wednesday 17th October 2012
View Replies!

Printing invicible JTable with Column removed - JTable.PrintMode.FIT_WIDTH problem

My JTable is a table with some columns including a checkbox column. When the user clicks on the print button, the program will create an invisible copy of the visible table, then add a rowsorter to exclude all the rows with a checkbox that is set to false. then remove the checkbox column from the table. For the table to print I manually change the size of the table (else the content will not print). That is how I set up the table, I hope it made sense. But it is when I set the table to print with JTable.PrintMode.FIT_WIDTH thats not working as it should. The table is not printed across the whole page, like it still believes that the removed column is still there, resulting in that the rigthmost column will be cut, and not all data will be printed. I don't have this problem when printing JTable.PrintMode.NORMAL. I hope my explanation made sense. I have tried a long time to fix this but without result. I'd be gratefull if someone could help me. Here is the code. edit: I have removed the code till someone who knows tells me it is okay (see the two posts below).
VIEWS ON THIS POST

213

Posted on:

Wednesday 17th October 2012
View Replies!

Remove key bindings from all JButtons

, In our application, we want to remove the keybinding which allows the Spacebar to act as a mouse click on the focused button. That is, by default, hitting Space will 'click' on the focused button. We want to change this behavior so that hitting Space does not act as a mouse click. We have figured out how to do this for individual buttons within application, e.g.: myButton.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "none");
VIEWS ON THIS POST

43

Posted on:

Wednesday 17th October 2012
View Replies!

JPopupMenu showing window decorations, how to remove?

Hi. I have a JPopupMenu instance which is showing window decorations. Does anyone have any idea how I can remove them or how I can access the parent component to turn decorations off getParent() returns null.
VIEWS ON THIS POST

80

Posted on:

Wednesday 17th October 2012
View Replies!

How to remove menuitem from context menu (SWT)

hi everybody can someone tell me how i can remove a menuitem from a context menu or even better how i can clear all items from a menu (like resetting the menu). i couldn't find any remove method or so. depending on the selected item i want different entries in my context menu. any ideas regards
VIEWS ON THIS POST

147

Posted on:

Thursday 18th October 2012
View Replies!

cannot resolve symbol

I am getting this erro when I compile my code. I have worked out all the other bugs and now understand where they came from, but this one is a little baffeling to me. I have not changed any of the code in the area of the line that is giving me the problem (JComboBox interest = new JComboBox(interestArray) . Any ideas cannot resolve symbol symbol: constructor JComboBox (java.lang.String) import javax.swing.*; //importing the ability to create and use a frame import java.awt.*; //importing the swing functions like the combo box import java.awt.event.*; import java.lang.String; import java.io.*; import java.math.*; public class MortgageFrame5 extends JFrame implements ItemListener, ActionListener, Runnable{ //setting up my variables String paythis; double monthly; int a; int t; double I; double total; int loop; double balance; String actInt; int totalGraph; int interestGraph; int principalGraph; int pie[]; int pieDegree[]; //creating lables, boxes, arrays, and buttons JLabel amountLabel = new JLabel ("House cost in dollars:"); JComboBox amount = new JComboBox();{ amount.addItem("$100,000"); amount.addItem("$125,000"); amount.addItem("$150,000"); amount.addItem("$175,000"); amount.addItem("$200,000"); amount.addItem("$225,000"); amount.addItem("$250,000"); amount.addItem("$275,000"); } JLabel tILabel = new JLabel ("Payment term and rate:"); String[] termsInterestArray = {"7 years at 5.35%", "15 years at 5.5%", "30 years at 5.75%"}; String[] termsArray = {"7 years", "15 years", "30 years"}; String interestArray = readData(); private String readData(){ String s = null; try{ File interestRate = new File("interestRate.txt"); FileInputStream fileStream = new FileInputStream(interestRate); BufferedReader stream = new BufferedReader(new InputStreamReader(fileStream)); s = new String(stream.readLine()); } catch (Exception e){ System.err.println("Could not read file."); } return s; } JComboBox tI = new JComboBox(termsInterestArray); JComboBox term = new JComboBox(termsArray); JComboBox interest = new JComboBox(interestArray); JButton calculate = new JButton("Calculate"); JButton quit = new JButton("Quit"); JLabel heading = new JLabel ("Payment | Loan Balance | Interest Paid"); JTextArea future = new JTextArea (180, 40); JScrollPane futureInfo = new JScrollPane(future); JCheckBox seperateCheck = new JCheckBox("Check to select term and interest seperately"); JCheckBox tICheck = new JCheckBox("Check to select term and interest together"); ButtonGroup select = new ButtonGroup(); public MortgageFrame5(){ //setting up the frame and frame characteristics setTitle("Mortgage calculator"); setSize(340,350); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); //user can see the box FlowLayout flo = new FlowLayout(); Container pane = getContentPane(); future.setLineWrap(true); select.add(seperateCheck); select.add(tICheck); //setting the default layout manager and adding everything to the container pane.setLayout(flo); pane.add(amountLabel); pane.add(amount); pane.add(tILabel); pane.add(tICheck); pane.add(tI); pane.add(seperateCheck); pane.add(term); pane.add(interest); pane.add(calculate); pane.add(quit); pane.add(heading); pane.add(futureInfo); setContentPane(pane); //setting up the listeners amount.addItemListener(this); tI.addItemListener(this); term.addItemListener(this); interest.addItemListener(this); seperateCheck.addItemListener(this); tICheck.addItemListener(this); calculate.addActionListener(this); quit.addActionListener(this); repaint(); // retrieving the interest rates from the file } //this is where the program will act upon the user selections public void itemStateChanged(java.awt.event.ItemEvent e){ } //This is where the calculate button functionality comes from public void actionPerformed(ActionEvent event){ if(event.getSource() == calculate){ String strA = (String)amount.getSelectedItem(); if (strA.equals("$100,000")){ a = 100000; } else if (strA.equals("$125,000")){ a = 125000; } else if (strA.equals("$150,000")){ a = 150000; } else if (strA.equals("$175,000")){ a = 175000; } else if (strA.equals("$200,000")){ a = 200000; } else if (strA.equals("$225,000")){ a = 225000; } else if (strA.equals("$250,000")){ a = 250000; } else if (strA.equals("$275,000")){ a = 275000; } if (seperateCheck.isSelected()){ String strT = (String)term.getSelectedItem(); if (strT.equals("7 years")){ t = 7*12; } else if (strT.equals("15 years")){ t = 15*12; } else if (strT.equals("30 years")){ t = 30*12; } String strI = (String)interest.getSelectedItem(); if (strI.equals("5.35%")){ I = 0.0535; } else if (strI.equals("5.5%")){ I = 0.055; } else if (strI.equals("5.75%")){ I = 0.0575; } } else if (tICheck.isSelected()){ String strT = (String)tI.getSelectedItem(); if (strT.equals("7 years at 5.35%")){ t = 7*12; I = 5.35; } else if (strT.equals("15 years at 5.5%")){ t = 15*12; I = 5.5; } else if (strT.equals("30 years at 5.75%")){ t = 30*12; I = 5.75; } } } total = ((I/1200) + (I/1200)/(Math.pow(1+(I/1200),t) -1)) * 100 * a; monthly = total/t; balance = total; actInt = ("$" + (Math.round((monthly * I)* 100) / 100.00)); //setting up the loop to run and print the information into the text area future.setText("\n"); for (int loop = 1; loop
VIEWS ON THIS POST

110

Posted on:

Thursday 18th October 2012
View Replies!

how to remove Jtable

Hi , I want to remove a Jtable which is painted on a frame. What problem i am facing is that when first time user selects a text file data of that file get populated into jtable. if user now again selects one file a new Jtable get opened and get populated. What I want is to remove that first one jtable.
VIEWS ON THIS POST

69

Posted on:

Thursday 18th October 2012
View Replies!

cannot find symbol...class ParseException

MaskFormatter formatter = null; try { formatter = new MaskFormatter("#########"); } catch (ParseException e) { e.printStackTrace(); }
VIEWS ON THIS POST

104

Posted on:

Monday 22nd October 2012
View Replies!

BackgroundPanel.java cannot be placed in BorderLayout.NORTH

i am trying to put a picture on the top of my swing GUI that stretches horizontally to fit the width of the window as it resizes http://www.camick.com/java/source/BackgroundPanel.java this is the code for a commonly used function that scales images to their components size. it works by overloading the paintcontainer class, which is called every time the window resizes, which then calls the paint class. they simply grab the size of the container and draw the image to those dimensions the image that needs to be resized must be placed in BorderLayout.NORTH, because the rest of my GUI is in BorderLayout.CENTER, but BackgroundPanel cant be placed in NORTH, the image disappears, even with a minimum size set. it cant be placed inside a panel inside a panel inside NORTH either. ive been reading over the code for BackgroundPanel and its driving me crazy i cant figure out why here is some short example code, not my program but it simplifies the problem: import java.awt.*; import javax.swing.*; import java.awt.event.WindowEvent; public class JPanel1 extends JFrame { public static void main(String[] args) { new JPanel1(); } public JPanel1() { enableEvents(AWTEvent.WINDOW_EVENT_MASK); add(mainJPanel()); pack(); setVisible(true); } //debug space center to streatch private JPanel mainJPanel() { JPanel JPanel = new JPanel(); BorderLayout layout = new BorderLayout(); this.setMinimumSize( new Dimension( 224, 224 ) ); JPanel.setLayout(layout); JPanel.add(mainJPanel2(),BorderLayout.NORTH); return(JPanel); } //debug space center to streatch private JPanel mainJPanel2() { JPanel JPanel = new JPanel(); BorderLayout layout = new BorderLayout(); JPanel.setLayout(layout); JPanel.add(JPanel2(),BorderLayout.CENTER); return(JPanel); } private JPanel JPanel2() { BorderLayout layout = new BorderLayout(); this.setLayout(layout); Toolkit toolkit = Toolkit.getDefaultToolkit(); Image duke = toolkit.getImage("sun.jpg"); BackgroundPanel panel = new BackgroundPanel(duke, BackgroundPanel.SCALED); //panel.setMinimumSize( new Dimension( 224, 224 ) ); this.setMinimumSize( new Dimension( 224, 224 ) ); GradientPaint paint = new GradientPaint(0, 0, Color.BLUE, 600, 0, Color.RED); panel.setPaint(paint); return panel; } //exit when closed public void processWindowEvent(WindowEvent event) { if(event.getID() == WindowEvent.WINDOW_CLOSING) System.exit(0); } }
VIEWS ON THIS POST

105

Posted on:

Monday 22nd October 2012
View Replies!

To make JLabel move

Hi! I'm making an applet using Swing and I have one JPanel on my JApplet. JApplet has slider whose moving makes drawn shape on JPanel to move. I would like to put text on that shape and make them move together when I move slider. I tried using JLabel, but i don't know how to make it move. I messed with gap settings, invoked slider.getValue() in .addGap, but it doesn't work. Any ideas... Greetings!
VIEWS ON THIS POST

51

Posted on:

Monday 22nd October 2012
View Replies!

how will we move from one page to another within the same window in Swing?

I am new to Swing. I am trying to understand it. My problem is, I have created one login form which has username and password fields in it, when ever user clicks submit button, it has to show another page within the same window. But for me whenever he clicks submit button in the login form page , another new window is opening. Please someone help me with this problem.
VIEWS ON THIS POST

116

Posted on:

Monday 22nd October 2012
View Replies!

ActionListener: Non-static variable 'this' cannot be referenced from a non-static context????

Hi ! I'm not sure why the below code is giving me the error message: 'non-static variable this cannot be referenced from a non-static context', which points to tl, my TimerListener, which implements ActionListener. Is 'this' implied somewhere there that I'm not seeing I'm not sure what 'this' would have to do with my TimerListener\t I've Googled extensively and can't really find any explanation in my text. Does anyone have any ideas or an explanation If need be, I can post my other classes, but I don't think that's the issue here.
VIEWS ON THIS POST

140

Posted on:

Monday 22nd October 2012
View Replies!

removeAllHighlights() not working

I can ADD highlights to a JTextArea all day. I'm reading annotation data out of the database, and creating Annotation instances... then I'm using those to create highlights on my JTextArea at the relevant indices. private void loadAnnotations(JTextArea ta){ ArrayList arAnnos = getAnnotationsById(String.valueOf(d.getDocumentID())); try { for (Annotation i : arAnnos){ ta.getHighlighter().addHighlight(i.getSelectionStart(), i.getSelectionEnd(), redPainter); } }catch (BadLocationException ex) { System.out.println("Bad Painter Location!"); } }
VIEWS ON THIS POST

34

Posted on:

Monday 22nd October 2012
View Replies!

warhammer 40k game(some bartender please move this to game forum)

hi, im making a very simple game based on the tabletop game Warhammer 40k this is my first java project and im starting very simple, a basic menu and a bckground with moveable images, ill add functionality later, anyways, i have read most of java head on(great book by the way) and know how to display bitmaps and a gui, but i dont know anything much beyond that, so what i want to do is when the user clicks a button on the gui, when they move their mouse onto the playing area, the selcted bitmap jumps to the mouse and follows it around the playing area till the user clicks, if anyone could give me some sample code or even just explain it to me, that would be great! __________________________________________________________________________ |!!!| |!!!| |!!!playing area!!!| |!!!| |!!!| |!!!| |!!!| |!!!| |!!!| |!!!| |!!!| |_________________________________________________________________________| |***************************GUI***********************************| |_________________________________________________________________________| sorry i just cant get this text representation to turn out right, it supposed to be a square playing area above a rectangular gui [ August 24, 2007: Message edited by: Frank McDeffer ] , sorry about that, anyways any reply would be greatly appreciated, and if you'd like more information on the game send me a private message, however i doubt if a very good version would be available soon, unlees the community REALLY comes through for me with answers
VIEWS ON THIS POST

41

Posted on:

Monday 22nd October 2012
View Replies!