JTextPanes added to JPanel

I have several JTextPanes added to a JPanel. I just want the JTextPane that is currently focused shd be painted(visible) fully irrespective of the order in which it is added to the JPanel.
My project is to develope a GUI similler to MS Powerpoint, using Java Swing
Thanks in Advance
anu

Hey,
Thank u.I solved that pbm.
But one more pbm araise coz of that i think.
Components caret & selected text are not visible.
is it coz of removing & then adding components to JPanel?
I've registered all listeners(Focus etc), when the components obj r created.
It was working before that. ie omitting 3 lines indicated by //new
anu
sample codes from JPanel
public void bringComponentToFront()
     if (focused == null)
     return;
     Vector tmpVector = new Vector();
     int compCount = getComponentCount();
     // bring component to front by inserting it first into the slide
     tmpVector.add((Component)focused);
     for(int i=0; i < compCount; i++) {
     Component tmpComp = getComponent(i);
     if (!tmpComp.equals(focused))
     tmpVector.add(tmpComp);
     removeAll();
     for(int i=0; i < compCount; i++)
     add((Component)(tmpVector.elementAt(i)));
     repaint();
//before focusing a new component,the current order of components r saved
public void saveOrder()
          int compCount = getComponentCount();
tmpVector1.clear();
          for(int i=0; i < compCount; i++)
          Component tmpComp=getComponent(i);
          tmpVector1.add(tmpComp);
//retriving the old order
public void retryOrder()
int compCount = getComponentCount();
removeAll();
          for(int i=0; i < tmpVector1.size(); i++)
          add((Component)(tmpVector1.elementAt(i)));
          repaint();
sample codes from JTextPane
//constructor
addFocusListener(new FocusListener)
     public void focusGained(FocusEvent e)
          parentSlide.saveOrder(); //new
          parentSlide.bringComponentToFront(); //new
     if (m_xStart>=0 && m_xFinish>=0)
     if (getCaretPosition()==m_xStart)
     setCaretPosition(m_xFinish);
     moveCaretPosition(m_xStart);
     else
     select(m_xStart, m_xFinish);
     public void focusLost(FocusEvent e)
     parentSlide.retryOrder(); //new
     m_xStart = getSelectionStart();
     m_xFinish = getSelectionEnd();
focused: currently focused Component(JTextPane)
parentSlide : current slide(JPanel) of PowerPoint
tmpVector1: globally declared

Similar Messages

  • Adding a JPanel from one class to another Class (which extends JFrame)

    Hi everyone,
    So hopefully I go about this right, and I can figure out what I'm doing wrong here. As an exercise, I'm trying to write a Tic-Tac-Toe (TTT) game. However, in the end it will be adaptable for different variations of TTT, so it's broken up some. I have a TTTGame.java, and TTTSquareFrame.java, and some others that aren't relavent.
    So, TTTGame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              addPanel = startSimple();
              if(!addPanel.isValid())
                   System.out.println("Something's wrong");
              contents.add(addPanel);
              setSize(300, 300);
              setVisible(true);
         public JPanel startSimple()
              mainSquare = new TTTSquareFrame(sides);
              mainSquarePanel = mainSquare.createPanel(sides);
              return mainSquarePanel;
    }and TTTSquareFrame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.Misc;
    public class TTTSquareFrame
         private JPanel squarePanel;
         private JButton [] squares;
         private int square, index;
         public TTTSquareFrame()
              System.out.println("Use a constructor that passes an integer specifying the size of the square please.");
              System.exit(0);
         public TTTSquareFrame(int size)
         public JPanel createPanel(int size)
              square = (int)Math.pow(size, 2);
              squarePanel = new JPanel();
              squarePanel.setLayout(new GridLayout(3,3));
              squares = new JButton[square];
              System.out.println(MIN_SIZE.toString());
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setRolloverEnabled(false);
                   squares[i].addActionListener(bh);
                   //squares[i].setMinimumSize(MIN_SIZE);
                   squares[i].setVisible(true);
                   squarePanel.add(squares[i]);
              squarePanel.setSize(100, 100);
              squarePanel.setVisible(true);
              return squarePanel;
    }I've successfully added panels to JFrame within the same class, and this is the first time I'm modularizing the code this way. The issue is that the frame comes up blank, and I get the message "Something's wrong" and it says the addPanel is invalid. Originally, the panel creation was in the constructor for TTTSquareFrame, and I just added the mainSquare (from TTTGame class) to the content pane, when that didn't work, I tried going about it this way. Not exactly sure why I wouldn't be able to add the panel from another class, any help is greatly appreciated.
    I did try and cut out code that wasn't needed, if it's still too much let me know and I can try and whittle it down more. Thanks.

    Yea, sorry 'bout that, I just cut out the parts of the files that weren't relevant but forgot to compile it just to make sure I hadn't left any remnants of what I had removed. For whatever it's worth, I have no idea what changed, but something did and it is working now. Thanks for your help, maybe next time I'll post an actual question that doesn't somehow magically solve itself.
    EDIT: Actually, sorry, I've got the panel working now, but it's tiny. I've set the minimum size, and I've set the size of the panel, so...why won't it respond to that? It almost looks like it's being compressed into the top of the panel, but I'm not sure why.
    I've compressed the code into:
    TTTGame.java:
    import java.awt.*;
    import javax.swing.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              mainSquare = new TTTSquareFrame(sides.intValue());
              contents.add(mainSquare);
              setSize(400, 400);
              setVisible(true);
    }TTTSquareFrame.java
    import java.awt.*;
    import javax.swing.*;
    public class TTTSquareFrame extends JPanel
         private JButton [] squares;
         private int square, index;
         private final Dimension testSize = new Dimension(50, 50);
         public TTTSquareFrame(int size)
              super();
              square = (int)Math.pow(size, 2);
              super.setLayout(new GridLayout(size, size));
              squares = new JButton[square];
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setMinimumSize(testSize);
                   squares[i].setVisible(true);
                   super.add(squares[i]);
              setSize(200, 200);
              setVisible(true);
    I've made sure the buttons are smaller than the size of the panel, and the panel is smaller than the frame, so...
    Message was edited by:
    macman104

  • Component added to JPanel is invisible

    i have a JPanel ( called panelMap ) on a JPanel ( called uProfile ) and im simply adding a component ( in this case a JLabel ) to panelMap in the constructor of uProfile. But the component never displays.
    the code is as follows :
    public uProfile( ) {
    initComponents();
    JLabel lbl = new JLabel();
    lbl.setText("blah");
    lbl.setLocation(20,20);
    this.panelMap.add( lbl );
    }

    Hi chalcoprite,
    u didn't set the label.setSize()
    since u r adding the component as a dynamic one i think u need that.
    then, if your panel layout is just Null, then there is no meaning for that setLocation() method.
    else, u have to set that component in NORTH or CENTER or SOUTH of that LayoutManager which u used.
    Also after u added one component, call the validate() and repaint() in the panel.
    like
    panelMap.validate(); and panelMap.repaint();
    this will work i think..

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

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

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

  • Help with adding a JPanel with multiple images to a JFrame

    I'm trying to make a program that reads a "maze" and displays a series of graphics depending on the character readed. The input is made from a file and the output must be placed in a JFrame from another class, but i can't get anything displayed. I have tried a lot of things, and i am a bit lost now, so i would thank any help. The input is something like this:
    20
    SXXXXXXXXXXXXXXXXXXX
    XXXX XXXXXXXXXXX
    X XXXXX
    X X XX XXXXXXXXXXXX
    X XXXXXXXXX XXX
    X X XXXXXXXXX XXXXX
    X XXXXX XXXXX XXXXX
    XX XXXXX XX XXXX
    XX XXXXX XXXXXXXX
    XX XX XXXX XXXXXXXX
    XX XX XXXXXXXX
    XX XXX XXXXXXXXXXXXX
    X XXXXXXXXXXXXX
    XX XXXXXXX !
    XX XXXXXX XXXXXXXXX
    XX XXXXXXX XXXXXXXXX
    XX XXXXXXXX
    XX XXXX XXXXXXXXXXXX
    XX XXXX XXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXX
    Generated by the Random Maze Generator
    And the code for the "translator" is this:
    package project;
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    public class Translator extends JFrame {
       private FileReader Reader;
       private int size;
       Image wall,blank,exit,start,step1,step2;
      public Translator(){}
      public Translator(File F){
      try {
           Reader=new FileReader(F);}
      catch (IOException e){
           JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
      try {
      size=Reader.read();
      System.out.write(size);}
      catch (IOException e){
           JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
      Toolkit theKit=Toolkit.getDefaultToolkit();
      wall=theKit.getImage("wall.gif");
      blank=theKit.getImage("blanktile.jpg");
      exit=theKit.getImage("exit.jpg");
      start=theKit.getImage("start.jpg");
      step1=theKit.getImage("start.jpg");
      step2=theKit.getImage("step1.jpg");
      JPanel panel=new JPanel(){
      public void paintComponent(Graphics g) {
      super.paintComponents(g);
      int ch=0;
      System.out.print("a1 ");
      int currentx=0;
      int currenty=0;
      try {ch=Reader.read();
          System.out.write(ch);}
      catch (IOException e){}
      System.out.print("b1 ");
      while(ch!=-1){
        try {ch=Reader.read();}
        catch (IOException e){}
        System.out.write(ch);
        switch (ch){
            case '\n':{currenty++;
                      break;}
            case 'X':{System.out.print(">x<");
                     g.drawImage(wall,(currentx++)*20,currenty*20,this);
                     break;}
           case ' ':{
                     g.drawImage(blank,(currentx++)*20,currenty*20,this);
                     break;}
            case '!':{
                     g.drawImage(exit,(currentx++)*20,currenty*20,this);
                      break;}
            case 'S':{
                     g.drawImage(start,(currentx++)*20,currenty*20,this);
                      break;}
            case '-':{
                     g.drawImage(step1,(currentx++)*20,currenty*20,this);
                      break;}
            case 'o':{
                      g.drawImage(step2,(currentx++)*20,currenty*20,this);
                      break;}
            case 'G':{ch=-1;
                      break;}
                  }//Swith
          }//While
      }//paintComponent
    };//Panel
    panel.setOpaque(true);
    setContentPane(panel);
    }//Constructor
    }//Classforget all those systems.out and that stuff, that is just for the testing
    i call it in another class in this way:
    public Maze(){
        firstFrame=new JFrame("Random Maze Generator");
        firstFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        (...)//more constructor code here
        Translator T=new Translator(savefile);
        firstFrame.add(T);
        firstFrame.getContentPane().add(c);
        firstFrame.setBounds(d.width/3,d.height/3,d.width/2,d.height/4);
        firstFrame.setVisible(true);
        c.setSize(d.width/2,d.height/4);
        c.show();
        }i know it may be a very basic or concept problem, but i can't get it solved
    thanks for any help

    Try this. It's trivial to convert it to use your images.
    If you insist on storing the maze in a file, just read one line at a
    time into an ArrayList than convert to an array and pass that to the
    MazePanel constructor.
    Any questions, just ask.
    import java.awt.*;
    import javax.swing.*;
    public class CFreman1
         static class MazePanel
              extends JPanel
              private final static int DIM= 20;
              private String[] mMaze;
              public MazePanel(String[] maze) { mMaze= maze; }
              public Dimension getPreferredSize() {
                   return new Dimension(mMaze[0].length()*DIM, mMaze.length*DIM);
              public void paint(Graphics g)
                   g.setColor(Color.BLACK);
                   g.fillRect(0, 0, getSize().width, getSize().height);
                   for (int y= 0; y< mMaze.length; y++) {
                        String row= mMaze[y];
                        for (int  x= 0; x< row.length(); x++) {
                             Color color= null;
                             switch (row.charAt(x)) {
                                  case 'S':
                                       color= Color.YELLOW;
                                       break;
                                  case 'X':
                                       color= Color.BLUE;
                                       break;
                                  case '!':
                                       color= Color.RED;
                                       break;
                             if (color != null) {
                                  g.setColor(color);
                                  g.fillOval(x*DIM, y*DIM, DIM, DIM);
         public static void main(String[] argv)
              String[] maze= {
                   "SXXXXXXXXXXXXXXXXXXX",
                   "    XXXX XXXXXXXXXXX",
                   "X              XXXXX",
                   "X  X XX XXXXXXXXXXXX",
                   "X    XXXXXXXXX   XXX",
                   "X  X XXXXXXXXX XXXXX",
                   "X  XXXXX XXXXX XXXXX",
                   "XX XXXXX XX     XXXX",
                   "XX XXXXX    XXXXXXXX",
                   "XX  XX XXXX XXXXXXXX",
                   "XX  XX      XXXXXXXX",
                   "XX XXX XXXXXXXXXXXXX",
                   "X      XXXXXXXXXXXXX",
                   "XX XXXXXXX         !",
                   "XX  XXXXXX XXXXXXXXX",
                   "XX XXXXXXX XXXXXXXXX",
                   "XX          XXXXXXXX",
                   "XX XXXX XXXXXXXXXXXX",
                   "XX XXXX XXXXXXXXXXXX",
                   "XXXXXXXXXXXXXXXXXXXX"
              JFrame frame= new JFrame("CFreman1");
              frame.getContentPane().add(new MazePanel(maze));
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setResizable(false);
              frame.setVisible(true);
    }

  • Adding a JPanel to a JCheckBox (that's not a typo)

    Happy Friday everyone! Time for another slightly ridiculous question from yours truly.
    Long story short, I'm trying to create a JCheckBox with three potential states instead of two: checked, unchecked, and undetermined. My eventual goal is to use this as a renderer in a JTree of options with sub-options, etc.
    Don't read this paragraph if you don't care about my ultimate goal and want to get onto the SSCCE: For example, the JTree might contain a node that represents "all animals" and then underneath it is a list of animals. The user would be able to select the "all animals" JCheckBox, which would then select all of the animal JCheckBoxes underneath it (I already have this part working perfectly). However, what should happen when the user goes into the structure and deselects "ducks" from the animal tree? Currently the "all animals" JCheckBox becomes deselected, but this doesn't seem very intuitive to me. So I'd like a third option that basically means "some of my children are selected, some are deselected". (My actual program has nothing to do with animals, but it's a fun example)
    The meat and potatoes of the problem: In order to simulate the third state of the JCheckBox, I thought I'd add to it a JPanel that painted an X (or a slash, or whatever means "indeterminate") on itself. The problem is, all sorts of interesting things start happening when I do this. The JPanel is quite large before any repainting goes on. After the first call to repaint (I simulate this by resizing the JFrame a tiny tiny tiny bit), the JPanel isn't visible at all. And after that, only the JPanel is visible.
    Am I missing something? Is there a better way to do what I'm trying to do?
    The SSCCE:
    import javax.swing.JFrame;
    import java.awt.Dimension;
    import javax.swing.JCheckBox;
    import javax.swing.JPanel;
    import java.awt.Graphics;
    import javax.swing.BoxLayout;
    import javax.swing.UIManager;
    public class TestCheckBoxPanel{
         public TestCheckBoxPanel(){
              try {
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
              catch (Exception e) {
                   e.printStackTrace();
              JFrame frame = new JFrame("Testing JCheckBox");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
              JCheckBox regularCheckBox = new JCheckBox("CheckBox", true);
              final JCheckBox panelCheckBox = new JCheckBox("PanelCheckBox", false);
              JPanel panel = new JPanel(){
                   public void paintComponent(Graphics g){
                        super.paintComponent(g);
                        //this almost works, but what happens if the JCheckBox
                        //is a different size on a different computer?
                        //is that even possible?
                        setMinimumSize(new Dimension(10, 10));
                        setMaximumSize(new Dimension(10, 10));
                        setPreferredSize(new Dimension(10, 10));
                        //this makes the JPanel huge, and makes me cry
                        setMinimumSize(new Dimension(panelCheckBox.getWidth(), panelCheckBox.getHeight()));
                        setMaximumSize(new Dimension(panelCheckBox.getWidth(), panelCheckBox.getHeight()));
                        setPreferredSize(new Dimension(panelCheckBox.getWidth(), panelCheckBox.getHeight()));
                        g.drawLine(0, 0, getWidth(), getHeight());
                        g.drawLine(getWidth(), 0, 0, getHeight());
                   } //end paintComponent
              }; //end new JPanel
              panelCheckBox.add(panel);
              frame.add(regularCheckBox);
              frame.add(panelCheckBox);
              frame.pack();
              frame.setVisible(true);     
         public static void main(String [] args){
              new TestCheckBoxPanel();
    }

    jduprez wrote:
    Hello,
    First thank you for the humourous wording.Haha, I figure if I'm going to ask ridiculous questions, the least I can do is ask them in an entertaining way!
    Admittedly though, your problem is more complex than it seem.That's what I was afraid of :(
    I don't see you setting the layout of the JCheckbox (viewed as a Container of the JPanel). I tried experimenting with setting the JCheckBox's layout. Using a null layout and absolute positioning actually ends up with a monstrous looking cut-in-half JCheckBox with no text.
    Arguably, you know that the bounds are initially (0,0,0,0), but relying on the 0,0 origin assumes the box is always on the left side (which is not true as a JCheckbox can have a different alignment/orientation/don't remember the term.That should actually be okay, I can assume that the box will be on the left side for these purposes.
    Moreover, setting the size with a fixed value does not account for what may happen to the checkbox if you stretch it, change the font, change the spacing,...Exactly. That's why I wanted to use the JCheckBox's width and height, which ends up making the JPanel quite large instead of just the size of the box. I'd much rather prefer using a width and height that would change with the JCheckBox's size.
    When you say you have already dealt with the 3-state problem, you mean you have designed a custom model? Sort of. I wrote a custom renderer and nodes for my JTree. Each node contains its state (selected, deselected, and undetermined) which changes when the user selects a node in the JTree, and the renderer is to return a Component based on that status. The setting of the state works fine, it's just figuring out what the renderer should return.
    Then your component is no more a JCheckbox. I mean, do you still need that it extends JCheckbox?That's a good point. I was using a JCheckBox just because it seemed like the most logical/intuitive component, but I could use anything. The node's selected status is independent of the JCheckBox's selected status (I set the JCheckBox based off the node's state).
    If not, one thing you could try is to implement a 3StateCheckBox as a JPanel, which contains...I think what I might try to do is simply use a JLabel with an icon, and then have three separate icons for the three states (I might even use images of JCheckBoxes, haha).

  • One JPanel is missing after adding two JPanels to a JFrame

    I have two classes, ScoreTableView and CardView, which both extends the JPanel class. ScoreTableView is used to show one table only, and CardView is to show a set of cards for a memory game. My objective is to separate the development of the panels, so that it will easier to modify either of them later. I add instances of these two class to the contentPane of my top level JFrame object. However, I can only see the ScoreTableView(which is supposed to show me a table only) on the top part of the frame, and the CardView panel never show up.
    ScoreTableView.java
      public ScoreTableView(int numberOfPlayer){
    //      Create a model of the data.
            scoreTable = new JTable();//this scoreTable is a JTable object
            scoreTable.setModel(scoreTableData);  //scoreTableData is my data    
            JScrollPane jsp = new JScrollPane(scoreTable);          
            p = this;
            p.setLayout(new BorderLayout());
            p.add(jsp, BorderLayout.CENTER);
        }CardView.java
    public CardView(int w, int h){
            cardWidth = w;
            cardHeight = h;
            JPanel cardPanel = new JPanel();
            cardPanel.setLayout(new GridLayout(cardWidth,cardHeight)); 
            CardImageButton[][] cardsButtons = new CardImageButton[cardWidth][cardHeight];
          // ... more other none GUI coiding 
             }Here's what I have in my main
            Container contentPane = jf.getContentPane();//jf is the JFrame object          
            contentPane.setLayout(new BorderLayout()); 
    //      create the score panel                 
            ScoreTableView scoreTableView = new ScoreTableView(4);
          contentPane.add( scoreTableView, BorderLayout.NORTH);
            //create the cards panel
            CardView cardPanel = new CardView(4,4);
            contentPane.add(cardPanel, BorderLayout.CENTER);
            jf.pack();
            jf.setVisible(true);      

    Sorry, but I copied the wrong files. Now both panels can show up, but the score table is on the NORTH, and the card panel is on the SOUTH(although I set it to CENTER and wish it can occupy the rest of the window), but the center part of the window has nothing. How can I get rid of the white space, so that the score panel can can 30% of the top part of the window(even after resize), and the card panel can occupy the remaining 70%? I can't attach pictures here, otherwise I can upload some screenshot to show you what's the problem I have. Thank you in advance.
    This is my CardView class, I didnt' copy all of them upstair.
    public class CardView extends JPanel{
        private int cardWidth;
        private int cardHeight;
        private CardModel cm;
        private JPanel cardPanel;
        public CardView(int w, int h){
            cardWidth = w;
            cardHeight = h;
            cardPanel = this;
            cardPanel.setLayout(new GridLayout(cardWidth,cardHeight)); 
            CardImageButton[][] cardsButtons = new CardImageButton[cardWidth][cardHeight];
            int[][] list  = init(cardWidth, cardHeight);       
            cm = new CardModel(list);
            int count = 0;
            for(int i=0;i<cardWidth;i++){
                for(int j=0;j<cardWidth;j++){
                    cardsButtons[i][j] = new CardImageButton("Press me"+count, cm, i, j, 0);
                    cardPanel.add(cardsButtons[i][j]);
                    count++;               
    public int[][] init(int n, int m){
            int[][] list  = {
                    {1, 2, 1, 1},
                    {2, 1, 2 , 2},
                    {1, 2, 1, 1},
                    {2, 1, 2 , 2} };
            return list;
        }This is from my main.
           //setup the content panel
            Container contentPane = jf.getContentPane();          
            contentPane.setLayout(new BorderLayout()); 
    //      create the score panel                 
            ScoreTableView scoreTableView = new ScoreTableView(4);
          contentPane.add( scoreTableView, BorderLayout.NORTH);
            //create the cards panel
            CardView cardPanel = new CardView(4,4);
            contentPane.add(cardPanel, BorderLayout.CENTER);
            jf.pack();
            jf.setVisible(true);   ScoreTableView.java
      public ScoreTableView(int numberOfPlayer){
    //      Create a model of the data.
    scoreTable = new JTable();//this scoreTable is a JTable object       
    scoreTable.setModel(scoreTableData);  //scoreTableData is my data            
    JScrollPane jsp = new JScrollPane(scoreTable);                  
    p = this;       
    p.setLayout(new BorderLayout());       
    p.add(jsp, BorderLayout.CENTER);   
    }

  • Adding customized JPanel's to a frame

    This seems like a very easy solution, but I've been looking around and can't find a way to solve it.
    Let's say I have a class like:
    public class StickyPerson extends JComponent {
        private int x, y;
         * Set coordinates for the sticky person
         * @param x Position x
         * @param y Position y
        public void setCoordinates(int x, int y) {
            this.x = x;
            this.y = y;
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.drawOval(this.x, this.y, 50, 50);
    }and in my main class I do like that:
          StickyPerson aPerson = new StickyPerson();
          aPerson.setCoordinates(90, 100);
          frame.add(aPerson);
          aPerson.setCoordinates(290, 100);
          frame.add(aPerson);The problem I'm dealing with is that only the last StickyPerson object is drawn. I've tested with other shapes as well and got the same result, only the last object is shown.
    It's clear that I'm making a mistake somewhere but I can't find where. Any ideas?
    Thank you
    Edited by: Raisen on Sep 10, 2009 12:00 AM

    Thanks for all the replies. After reading more about the layout managers, I found out that in this specific project, I need to set the layout manager to null because I'm going to be dealing with drawings all over my frame.
    I've added setBounds and setSize inside the paintComponent method but somehow, whenever I add the component to the frame, the method is never called.
    Example:
    public class StickyPerson extends JComponent {
        public StickyPerson(JFrame aFrame) {
            super();
            insets = aFrame.getInsets();
        public void paintComponent (Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            GradientPaint redtowhite = new GradientPaint(0,0,Color.GRAY,
                    100, 0, Color.WHITE);
            g2.setPaint(redtowhite);
            g2.fill (new Ellipse2D.Double(this.x, this.y, this.w, this.h));
            g2.setColor(Color.BLACK);
            g2.drawString(this.text, this.x+25, this.y+25);
            this.setSize(w, h);
            this.setBounds(10 + this.insets.left, 50 + this.insets.top,
                    this.w, this.h);
    }and in my main code:
          JFrame frame = new JFrame("Example");
          frame.getContentPane().setLayout(null);
          frame.setSize(550, 400);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          StickyPerson stickyPerson = new StickyPerson(frame);
          stickyPerson.setCoordinates(10, 20, 200, 40);
          stickyPerson.setText("Hello World");
          frame.add(stickyPerson);
    code}
    I've omitted the other irrelevant methods to shorten the code. I've attached breakpoints inside the paintComponent method but it never reaches it. I've tried to use repaint(), validate(), repack().                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • JTextPane adding hyperlinks

    Hello everyone. I currently have a simple chat window implemented using a JTextPane. A chat message consists of a star image, timestamp, username, and the message. I am attempting to allow other people in the chat room to click on the username of the message, and obtain additional information about that person. Here's my current code:
         public void initAttributeSets()
              green = new SimpleAttributeSet();
              StyleConstants.setForeground(green, chatColorGreen);
              StyleConstants.setBold(green, false);
              StyleConstants.setFontSize(green, chatFontSize);
              green_bold = new SimpleAttributeSet();
              StyleConstants.setForeground(green_bold, chatColorGreen);
              StyleConstants.setBold(green_bold, true);
              StyleConstants.setFontSize(green_bold, chatFontSize);
         public void setLobbyChatMessage(int star, String username, String message)
              Document doc = lobbyChatPane.getStyledDocument();
              try
                   // user message, display as green text
                   StyleConstants.setIcon(starIcon,imageIcons[star-1]);
                   doc.insertString(doc.getLength(), "star", starIcon);
                   doc.insertString(doc.getLength(), " [timestamp] " + username + "> ", green_bold);
                   doc.insertString(doc.getLength(), message + "\n", green);
              catch(BadLocationException exp)
                   // do nothing
              lobbyChatPane.setCaretPosition( doc.getLength() );
         private SimpleAttributeSet green;
         private SimpleAttributeSet green_bold;The hyperlink would not effect the JTextPane window in any way. I wish to implement using hyperlinkUpdate(HyperlinkEvent event) to determine the usename and display information using some kind of Dialog. I have been having a very hard time getting the hyperlink to work with the other components. Any suggestions/solutions would be appreciated, thanks.

    Doesn't anyone have a hint for me here?

  • Adding a JPanel to a JScrollPane?

    I have a JPanel which may hold a lot of components, this may run off the end of the window so I want to add the components to a JPanel and the JPanel to a JScrollPane to deal with this can anyone tell me why the below code won't do this?
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.ScrollPaneConstants;
    public class Test extends JScrollPane
         public JFrame testFrame;
         public JPanel testPanel;
         public JCheckBox checkBox;
         public static void main(String[] args)
              new Test();
         public Test()
              testFrame = new JFrame("test");
              //testFrame.getContentPane().setLayout(null);
              testPanel = new JPanel();          
              JScrollPane sp = new JScrollPane(testPanel);
              //add the panel to the scroll pane
              //sp.setViewportView(testPanel);
              //sp.getVerticalScrollBar();
              this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
              this.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              testFrame.getContentPane().add(sp);
              //add the scroll pane to the frame
             JLabel lbl1 = new JLabel("blah");
             testPanel.add(lbl1);
            testFrame.getContentPane().add(testPanel);
             for(int i=0; i==20; i++)
                   checkBox = new JCheckBox(String.valueOf(i));
                  //checkBox.addItemListener(this);
                  JTextField txt1 = new JTextField(10);
                  txt1.setText("hello world");
                 testPanel.add(checkBox);
                testPanel.add(txt1);
            testPanel.validate();
            testPanel.setVisible(true);
            testFrame.pack();
            testFrame.setVisible(true);
            testFrame.setSize(100, 200);
            testFrame.show();
    }

    Actually not extending JScrollPane means that
    this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    this.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    raised compile errors so you've clearly not bothered to run it.
    Anyway, I figured out the solution, for anyone who may find it useful here it is:
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    public class Test
         public JFrame testFrame;
         public JPanel testPanel;
         public JCheckBox checkBox;
         public JButton btnDone;
         public static void main(String[] args)
              new Test();
         public Test()
              testFrame = new JFrame("test");
              testPanel = new JPanel();
              testPanel.setLayout(new GridBagLayout());
              JScrollPane sp = new JScrollPane();
              GridBagConstraints gridBagConstraints = new GridBagConstraints();
             JLabel lbl1 = new JLabel("blah");
             testPanel.add(lbl1);
             for(int i=0; i<20; i++)
                   checkBox = new JCheckBox(String.valueOf(i));
                  //checkBox.addItemListener(this);
                  JTextField txt1 = new JTextField(10);
                  txt1.setText("hello world");
                 gridBagConstraints.gridx = 0;
                 gridBagConstraints.gridy = i+1;
                 testPanel.add(checkBox, gridBagConstraints);
                 gridBagConstraints.gridx = 1;
                 gridBagConstraints.gridy = i+1;
                 testPanel.add(txt1, gridBagConstraints);
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridy = gridBagConstraints.gridy+1;
            testPanel.add(btnDone = new JButton("Done"), gridBagConstraints);
              sp.setViewportView(testPanel);
             testFrame.getContentPane().add(sp);
             //btnDone.addActionListener(this);
            testPanel.validate();
            testFrame.pack();
            testFrame.setVisible(true);
            testFrame.setSize(200, 300);
            testFrame.show();
    }

  • Adding a jPanel to another jPanel help

    I have a class NavigationButtonsClass which has the navigationalPanel which in turn has buttons back, next ... etc.
    public JPanel navigationalPanel = new JPanel();
    I have another class ProjectClass in which I gave the following
    NavigationButtonsClass newNavigationButtonsClass = new NavigationButtonsClass();
    jPanel1.add(newNavigationButtonsClass.navigationalPanel, new XYConstraints(0, 0, 795, -1));
    this.getContentPane().add(jPanel1, new XYConstraints(1, 420, 798, 45));
    Is something wrong here. I am not able to see the navigationalPanel.
    Thanks.

    Modify ur NavigationButtonsClass like,
    public class NavigationButtonsClass extends JPanel
       add(backButton);
       add(cancelButton);
    }Now in ur ProjectClass
    this.getContentPane().add(new  NavigationButtonsClass(),BorderLayout.SOUTH);I have assumed ur Project class extends JFrame...

  • Adding 2 JPanels, different classes

    Hi,
    I have 3 different classes in 3 files:
    public class Trainer {
      public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
          f.getContentPane().add(t);
          f.pack();
    }...plus...
    public class Test extends JPanel {
      public int testing(int n) {
        return 0;
    }...and...
    public class Game extends Test implements MouseListener, MouseMotionListener {
        Game() {
            setPreferredSize(new Dimension(800, 600));
            addMouseListener(this);
            addMouseMotionListener(this);
    (...)I would like to add 2 JPanels side by side to the class "Game". I am not allowed to modify "Test" and "Trainer". Class "Trainer" incorporates the main-method.
    How could I do this?
    Thanks for your help!

    Thanks for your replies, they were really helpful :)
    My last question to this topic: I would like to set a background-color for my 2 JPanels - however, the color isn't applied:
        Game() {
            setPreferredSize(new Dimension(800, 600));
            setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
            JPanel actionPanel = new JPanel() { public void paint(Graphics g) {
                actionPanel_paint(g);
            actionPanel.addMouseListener(this);
            actionPanel.addMouseMotionListener(this);
            actionPanel.setBackground(new java.awt.Color(153, 204, 255));
            JPanel statusPanel = new JPanel() { public void paint(Graphics g) {
                statusPanel_paint(g);
            statusPanel.setBackground(new java.awt.Color(204, 255, 204));
            add(actionPanel);
            add(statusPanel);
        public void actionPanel_paint(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);       
            Ellipse2D.Double testCircle_action = new Ellipse2D.Double(100, 100, 20, 20);
            g2.setColor(Color.RED);
            g2.draw(testCircle_action);
            g2.fill(testCircle_action);
        public void statusPanel_paint(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            Ellipse2D.Double testCircle_status = new Ellipse2D.Double(100, 100, 20, 20);
            g2.setColor(Color.BLACK);
            g2.draw(testCircle_status);
            g2.fill(testCircle_status);
        }

  • Why JTextPane not obtaining the listeners from the parent JPanel?

    Hi All,
    When I add JTextPane to the JPanel and adding MouseListeners to the JPanel, it is not responding when I click on JTextPane. If I add JLabel or JButton, it is working fine. I need to add the mouse listeners to the panel only. Can anybody has any idea on this? Here is the code what I wrote:
    class Example extends JPanel implements MouseListener {
    public Example() {
    setLayout(null);
    JTextPane pane = new JTextPane();
    pane.setBounds(20,20,50,50);
    add( pane);
    addMouseListener(this);
    public void mousePressed(MouseEvent me) {
    // Here it is not entering into mousePressed at all
    if(getCompnentAt(me.getPoint()) instanceof JTextPane) {
    System.out.println("pressed on textpane");
    Thanks in advance,
    Kishore.

    We are not Apple iOS programmers.  Just device users like yourself.
    feedback.apple.com is where you should send suggestions.

  • JScrollPane (added to a JPanel, which paints) is visible but does nothing

    Hi. I am writing a program that reads data from files and does paiting using the info. The top level window is a JFrame, which is divided into two parts - A Box which contains the buttons through which the user interacts and a JPanel on which the painting is done. I have added the JPanel to a JScrollPane, but have run into problems there. The JScrollPane is visible (both policies always visible) but it does nothing. I understand that when the drawing is fitting, the ScrollPane is not used. But even if I make the window small or draw something that is not visible in the normal are, the JScrollPane doesn't work. In fact, no knob is visible on either of the two scrollbars. I am pasting the relevant code below:
    //import
    public class MainWindow extends JFrame {
        public static void Main(String[] args) {
            new MainWindow();
        //Declare all the variables here.
        private Box buttionBox;
        private JScrollPane scroller;
        private HelloPanel drawingPanel;   
        //other variables
        //The constructor for the class MainWindow.
        public MainWindow() {
           initComponents();
            this.setLayout(new BorderLayout());
            this.setPreferredSize(new Dimension(900,670));
            //buttonBox containts the buttons - not very relevant to this problem.
            this.getContentPane().add(buttonBox, BorderLayout.WEST);
            //scroller is the JScrollPane
            this.getContentPane().add(scroller, BorderLayout.CENTER);       
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setTitle("My Title");       
            this.setVisible(true);
            this.pack();       
        public void initComponents() {
            buttonBox = Box.createVerticalBox();
            //instantiate the buttons here and add them to the ButtonBox.
            //The event listeners instantiated. Not relevant.       
            //The various components are assigned their appropriate event listeners here.
             //Not relevant.
    //Now adding all the buttons to the box with proper spacing.
            buttonBox.add(Box.createVerticalStrut(20));
            //This is the drawing panel on which the drawing will be done.
            drawingPanel = new HelloPanel();
            scroller = new JScrollPane(drawingPanel);
                    scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            scroller.getHorizontalScrollBar().setUnitIncrement(10);
            scroller.getVerticalScrollBar().setUnitIncrement(10);
        //This inner class is used to define and implement the event listener for handling the checkboxes.
        private class checkBoxListener implements ItemListener{
            public void itemStateChanged(ItemEvent e){
                 drawingPanel.repaint();
                    //Implement actions. Irrelevant
        //This private class is used to define and implement the event listener for the buttons.
        private class buttonListener implements ActionListener {
            //Do this when the button which has an instance of this class as its listener is clicked.       
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == saveStructureButton){
                  //Implement action. Irrelvant.
        //The panel on which the drawings are done.
        private class HelloPanel extends JPanel {
            //This JPanel is used for drawing the image (for the purpose of saving to disk).
            JComponent c;    //For image. Irrelevant.
            public HelloPanel(){           
                c = this;   //This is necessary for drawing the image to be saved to disk.
                this.setBackground(Color.WHITE);
            //This is the method that actually paints all the drawings whenever a.
            //The shapes theselves can be defined somewhere else, but that paint method must be invoked from here.
            public void paintComponent(Graphics g){
                super.paintComponent(g);    //First of all, clear the panel.
                Graphics2D g2 = (Graphics2D) g;
                g2.fill(new Rectangle2D.Double(40,40,100,100));    //Just for this post.
                g2.drawString("Text", 750, 750);    //To test the scrollpane.
    } I hope this helps you get an idea of what I am trying to do and what the problem might be. Any help would be really appreciated. I have spent hours on this and I have no idea why it doesn't work.
    The actual code is much bigger, so if you need any extra information, please tell me.

    HelloPanel should provide a "public Dimension getPreferredSize()" method.
    With your code you create a simple JPanel and want to draw outside of it, but you never tell the JScrollPane that your HelloPanel is actually bigger than it seems, that's why it does not feel the need to add scroll bars.
    Here's the working code:
    //import
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    public class MainWindow extends JFrame {
        public static void main(String[] args) {
            new MainWindow();
        //Declare all the variables here.
        private Box buttionBox;
        private JScrollPane scroller;
        private HelloPanel drawingPanel; 
        //other variables
        //The constructor for the class MainWindow.
        public MainWindow() {
           initComponents();
            this.setLayout(new BorderLayout());
            this.setPreferredSize(new Dimension(900,670));
            //buttonBox containts the buttons - not very relevant to this problem.
            //this.getContentPane().add(buttonBox, BorderLayout.WEST);
            //scroller is the JScrollPane
            this.getContentPane().add(scroller, BorderLayout.CENTER);       
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setTitle("My Title");       
            this.setVisible(true);
            this.pack();       
        public void initComponents() {
            //buttonBox = Box.createVerticalBox();
            //instantiate the buttons here and add them to the ButtonBox.
            //The event listeners instantiated. Not relevant.       
            //The various components are assigned their appropriate event listeners here.
             //Not relevant.
    //Now adding all the buttons to the box with proper spacing.
            //buttonBox.add(Box.createVerticalStrut(20));
            //This is the drawing panel on which the drawing will be done.
            drawingPanel = new HelloPanel();
            scroller = new JScrollPane(drawingPanel);
                    scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            scroller.getHorizontalScrollBar().setUnitIncrement(10);
            scroller.getVerticalScrollBar().setUnitIncrement(10);
        //This inner class is used to define and implement the event listener for handling the checkboxes.
        private class checkBoxListener implements ItemListener{
            public void itemStateChanged(ItemEvent e){
                 drawingPanel.repaint();
                    //Implement actions. Irrelevant
        //This private class is used to define and implement the event listener for the buttons.
        private class buttonListener implements ActionListener {
            //Do this when the button which has an instance of this class as its listener is clicked.       
            public void actionPerformed(ActionEvent e) {
                //if (e.getSource() == saveStructureButton){
                  //Implement action. Irrelvant.
        //The panel on which the drawings are done.
        private class HelloPanel extends JPanel {
            //This JPanel is used for drawing the image (for the purpose of saving to disk).
            JComponent c;    //For image. Irrelevant.
            public HelloPanel(){           
                c = this;   //This is necessary for drawing the image to be saved to disk.
                this.setBackground(Color.WHITE);
            //This is the method that actually paints all the drawings whenever a.
            //The shapes theselves can be defined somewhere else, but that paint method must be invoked from here.
            public void paintComponent(Graphics g){
                super.paintComponent(g);    //First of all, clear the panel.
                Graphics2D g2 = (Graphics2D) g;
                g2.fill(new Rectangle2D.Double(40,40,100,100));    //Just for this post.
                g2.drawString("Text", 750, 750);    //To test the scrollpane.
         public Dimension getPreferredSize()
         return new Dimension(750,750);
    }

  • JTextPane on JPanel with MouseListener doesn't register MouseClicked

    I have a JTextPane on a JPanel. The JPanel has a MouseListener on it. If I click anywhere on the JPanel it successfully calls MouseClicked, except when I click on the JPanel over the JTextPane. When I click on the JTextPane, nothing happens. What is it about the JTextPane that my MouseEvents are not being fired when I click on it in the JPanel?
    Thanks!

    Events go to the component that has focus. By default
    a JLabel isn't focusable so I guess the event goes to
    the panel.Ok, that's very interesting. I extrapolated that a bit further and set the focusable property of my JTextPane to false, but unfortunately that didn't cause it to behave any more like a JLabel, with respect to the MouseListener on the JPanel.

Maybe you are looking for