Hi everyone!
I'm experiencing some trouble with a fairly simple problem I guess. First of all, I'm not a real expert when it comes to java, but I would like to learn it mostly by self study. And I'm sorry for the lots of code, but I can't really specify where my problem is exactly..

From rule 580 and further, I would like to draw something on my panel. But I'm not able to draw anything. But when I do a System.out.println() it seems that the program DOES run trough this code. I guess the problem is with the extra included panels, but I really can't figure out where exactly.

Thanks in advance!

package project;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
import java.io.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.JFileChooser;
import javax.swing.event.ChangeEvent;
import javax.swing.filechooser.FileFilter;


public class Main extends JFrame {

    public static void main(String[] args) {

        JFrame frame = new Main();
        frame.setTitle("Animatieproject, 3ICT1");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new Panel());
        frame.setSize(720, 540);
        frame.setVisible(true);
        frame.setMinimumSize(new Dimension(720,540)); //Minimum grootte instellen

    }
}

//////

class Panel extends JPanel{

    private JPanel paneelNoord,paneelZuid,paneelZuidCenter,paneelZuidWest,paneelNoordTop,paneelCentrum;
    private JButton openBestand,debugButton,playButton,pauseButton;
    private JLabel labelMetronome,labelBPM,labelMusic,labelBestandsnaam,dummyLabel;
    private JSlider sliderBPM;
    private JCheckBox geluidAanUit;
    private Timer timer;
    private DrumLijn drumLijn;
    private Cursor cursor;
    private int base = 120,timerCounter;

    public Panel() {

        drumLijn = new DrumLijn(base);
        cursor = new Cursor(base);

        timer = new Timer (1, new TimerHandler());

        //Keylistener toevoegen
        addKeyListener(new ToetsenbordHandler());

///////Begin: Layout van het paneel instellen///////
        setLayout( new BorderLayout() );

        paneelNoord = new JPanel();
        paneelNoord.setLayout(new GridLayout(3,1,0,0));
        paneelNoordTop = new JPanel();
        paneelNoordTop.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
        Border spatieNoord = BorderFactory.createEmptyBorder(5,70,10,70);
        paneelNoord.setBorder(spatieNoord);

        debugButton = new JButton("Debugbutton");
        ImageIcon open = new ImageIcon("images/openButton.png");
        ImageIcon play = new ImageIcon("images/playButton.png");
        ImageIcon pause = new ImageIcon("images/pauseButton.png");
        openBestand = new JButton("Open bestand",open);
        openBestand.addActionListener(new ButtonHandler());
        dummyLabel = new JLabel("     ");
        playButton = new JButton("Play",play);
        playButton.addActionListener(new ButtonHandler());
        dummyLabel = new JLabel("   ");
        pauseButton = new JButton("Pause",pause);
        pauseButton.addActionListener(new ButtonHandler());
        labelBestandsnaam = new JLabel("Nog niets geopend");
        //paneelNoordTop.add(debugButton);
        paneelNoordTop.add(openBestand);
        paneelNoordTop.add(playButton);
        paneelNoordTop.add(pauseButton);
        paneelNoordTop.add(dummyLabel);
        paneelNoordTop.add(labelBestandsnaam);
        labelBPM = new JLabel("Beats per minute");

        sliderBPM = new JSlider(JSlider.HORIZONTAL,10,160,10);
        sliderBPM.setMajorTickSpacing(10);
        sliderBPM.setMinorTickSpacing(2);

        sliderBPM.setPaintLabels(true);
        sliderBPM.setPaintTicks(true);
        sliderBPM.setEnabled(false);
        sliderBPM.addChangeListener(new SlideHandler());

        paneelNoord.add(paneelNoordTop);
        paneelNoord.add(labelBPM);
        paneelNoord.add(sliderBPM);

        paneelCentrum = new JPanel();
        paneelCentrum.setBackground(Color.red);

        paneelZuid = new JPanel();
        paneelZuid.setLayout(new BorderLayout() );
            paneelZuidCenter = new JPanel();
            labelMetronome = new JLabel("Metronome");
            paneelZuidCenter.add(labelMetronome);

            paneelZuidWest = new JPanel();
            paneelZuidWest.setLayout(new GridLayout(2,1, 0,5));
            Border spatieZuidWest = BorderFactory.createEmptyBorder(5,10,20,0);
            paneelZuidWest.setBorder(spatieZuidWest);
            labelMusic = new JLabel("Music:");

            geluidAanUit = new JCheckBox("Muziek aan/uit");
            geluidAanUit.setEnabled(false);
            geluidAanUit.addItemListener(new CheckboxHandler());
            paneelZuidWest.add(labelMusic);
            paneelZuidWest.add(geluidAanUit);

            paneelZuid.add(paneelCentrum,BorderLayout.CENTER);
            paneelZuid.add(paneelZuidWest,BorderLayout.WEST);

        add(paneelNoord,BorderLayout.NORTH);
        add(paneelCentrum,BorderLayout.CENTER);
        add(paneelZuid,BorderLayout.SOUTH);
///////Einde: Layout van het paneel instellen///////


    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        drumLijn.teken(g);
        drumLijn.paintComponent(g);
        requestFocusInWindow(); //Focus leggen op het paneel, niet op het venster!
                                //Belangrijk voor de ToetsenbordHandler
    }

    class SlideHandler implements ChangeListener{
        public void stateChanged(ChangeEvent se){
            drumLijn.setBPM(sliderBPM.getValue()); //BPM opnieuw instellen
            labelBPM.setText("Beats per minute: " + sliderBPM.getValue());
            
        }
        
    }

    class ToetsenbordHandler extends KeyAdapter {
        public void keyPressed(KeyEvent ke) {

            switch (ke.getKeyCode()) {
                case KeyEvent.VK_DOWN:
                case KeyEvent.VK_LEFT:
                    //BPM verlagen met 2 beats per minute (als mogelijk)
                    drumLijn.getBPM();
                    if (sliderBPM.isEnabled()==true){ // We mogen enkel aanpassen als de slider enabled is!
                        if(drumLijn.getBPM()>10){ //Kunnen we nog verlagen?
                        drumLijn.setBPM(drumLijn.getBPM()-1);
                        sliderBPM.setValue( drumLijn.getBPM());
                        sliderBPM.setEnabled(true);
                        System.out.println("BPM set: " +drumLijn.getBPM());
                        labelBPM.setText("Beats per minute: " + drumLijn.getBPM());
                        }
                    }
                    break;
                case KeyEvent.VK_UP:
                case KeyEvent.VK_RIGHT:
                    //BPM verhogen met 2 beats per minute
                    if (sliderBPM.isEnabled()==true){ // We mogen enkel aanpassen als de slider enabled is!
                        if(drumLijn.getBPM()<=159){ //Kunnen we nog verhogen?
                        drumLijn.setBPM(drumLijn.getBPM()+1);
                        sliderBPM.setValue( drumLijn.getBPM());
                        System.out.println("BPM set: " + drumLijn.getBPM());
                        labelBPM.setText("Beats per minute: " + drumLijn.getBPM());
                        }
                    }
                    break;
            }
            requestFocusInWindow();
        }

    }

    class ButtonHandler implements ActionListener {
        public void actionPerformed( ActionEvent e ) {

            if(e.getSource()== openBestand){
                File file = null;
                BufferedReader in;
                JFileChooser fc = new JFileChooser();
                FileFilter filter1 = new ExtensionFileFilter("JPJ - Java Project", new String[] { "JPJ"});
                fc.setFileFilter(filter1);
                int returnVal = fc.showOpenDialog(Panel.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    file = fc.getSelectedFile();
                    //System.out.println(file);
                    drumLijn.uitlezen(file.toString(),fc.getSelectedFile().getName());
                    drumLijn.setFilename(file.toString(), fc.getSelectedFile().getName()); //De locatie en filename setten
                    sliderBPM.setValue(drumLijn.getBPM());
                    labelBPM.setText("Beats per minute: " + drumLijn.getBPM());
                    sliderBPM.setEnabled(true);
                    geluidAanUit.setEnabled(true);
                    //Songtitel zetten, ook meteen de extensie van 4 karakters wissen
                    labelBestandsnaam.setText("Song: " + fc.getSelectedFile().getName().toString().substring(0,  fc.getSelectedFile().getName().toString().length()-4));
                }

                if (file != null) {
                    try {
                        in = new BufferedReader(new FileReader(file));
                        in.close();
                    } catch (FileNotFoundException fnfe) {
                        System.out.println("Kan bestand niet vinden");
                    } catch (IOException ioe) {
                        System.out.println("Fout bij het lezen of sluiten bestand");
                        ioe.printStackTrace();
                    }
                }
             repaint();
            }

            if(e.getSource()== playButton){
                if (drumLijn.getBPM()!=0){ //Er is al een nummer geselecteerd?
                    timer.start();
                }
            }

            if(e.getSource()== pauseButton){
                timer.stop();
            }

            requestFocusInWindow();
        }
    }

    class CheckboxHandler implements ItemListener{
        public void itemStateChanged(ItemEvent chk){
            if (geluidAanUit.isSelected()==true){
                System.out.println("Geluid: aan");
            }
            else {
                System.out.println("Geluid: uit");
            }
            requestFocusInWindow();
        }
    }

    class TimerHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            //actie
           
                timerCounter++;
                    if (timerCounter%9==8){ //Bij elke 9 miliseconden naar de volgende pixel (of bar)
                        if (cursor.getcursorXpositie()<576){ // Einde van de 'bar'?
                           cursor.setcursorXpositie(cursor.getcursorXpositie()+1);

                           if (cursor.getcursorXpositie()%100==8){
                           System.out.println(cursor.getcursorXpositie());
                               }
                        }
                        else{ //Ja: terug van 0 beginnen
                            cursor.setcursorXpositie(0);
                        }
                        
                    }
                
          

            //System.out.println(timerCounter);
            repaint(); //SIM: repaint() zodat alles op het scherm 'geupdatet' wordt

        }

    }

    class ExtensionFileFilter  extends FileFilter {
  String description;

  String extensions[];

  public ExtensionFileFilter(String description, String extension) {
    this(description, new String[] { extension });
  }

  public ExtensionFileFilter(String description, String extensions[]) {
    if (description == null) {
      this.description = extensions[0];
    } else {
      this.description = description;
    }
    this.extensions = (String[]) extensions.clone();
    toLower(this.extensions);
  }

  private void toLower(String array[]) {
    for (int i = 0, n = array.length; i < n; i++) {
      array[i] = array[i].toLowerCase();
    }
  }

  public String getDescription() {
    return description;
  }

  public boolean accept(File file) {
    if (file.isDirectory()) {
      return true;
    } else {
      String path = file.getAbsolutePath().toLowerCase();
      for (int i = 0, n = extensions.length; i < n; i++) {
        String extension = extensions[i];
        if ((path.endsWith(extension) && (path.charAt(path.length() - extension.length() - 1)) == '.')) {
          return true;
        }
      }
    }
    return false;
  }
}

}

///////////

class DrumLijn extends JPanel{

    private ArrayList bars,noteSet,aantalNoteset;
    private int index1,index2,bpm,aantalBars,hulpInt,hulpInt2;
    private int base,xPos,yPos;
    private boolean eersteRegel=true,hulpBoolean;
    private char noteLetter;
    private Note note;

    private String bpmString,hulpString,regel,filename,fileLocation;
    BufferedReader in;

    public DrumLijn(int base) {

        this.base = base;
        bars = new ArrayList();
        noteSet = new ArrayList();
        aantalNoteset = new ArrayList();
    }

///////////

    public void uitlezen(String file, String fileName){

        //Alle arrayLists terug leeg maken
        aantalNoteset.clear();
        bars.clear();
        noteSet.clear();
        eersteRegel=true;

            try {
                in = new BufferedReader(new FileReader(file));
                while ((regel = in.readLine()) != null) {
                    
                    //Elke regel wegschrijven naar de arraylist, behalve de eerste (dit is de BPM)
                    if (eersteRegel==true){
                        index1 = nthOccurrence(regel, '#', 0);
                        index2 = nthOccurrence(regel, '#', 1);
                        bpmString = regel.substring(index1+1,index2);
                        bpm = Integer.parseInt(bpmString);
                        System.out.println("BPM: "+ bpm);
                        eersteRegel=false; //Volgende keer verder gaan met de else

                    }
                    else{
                      bars.add(regel);
                    }
                    
                }
                in.close();
                convertToBar(); //Alle net ingelezen gegevens converteren naar een 'bar'
                } catch (FileNotFoundException e) {
                System.out.println("Kan het opgegeven bestand niet vinden");
                } catch (IOException e) {
                System.out.println("Fout bij het inlezen of sluiten bestand");
                e.printStackTrace();
            }


    }

    ///////////

    public void convertToBar(){
        ////////Elke 'bar' verder aanpassen tot makkelijker uitlezen bij de converToHit
        ////////Elke 'bar' onderverdelen in de 4 notesets

        //Aantal bars bepalen
        aantalBars = bars.size() -2;
        System.out.println("Aantal bars: " + bars.size());

        //Elke bar doorlopen
        for(int i=0;i<bars.size();i++){
        //:x: wissen op het begin van elke bar
        index2 = nthOccurrence(bars.get(i).toString(), ':', 1);

        //set(positie, waarde), waarde=substring vanaf de : tot het einde
        bars.set(i,bars.get(i).toString().substring(index2+1,bars.get(i).toString().length()));
        //System.out.println("Bar nummer " + i + ": " + bars.get(i));

            //Elke noteSet apart uitlezen (4 van deze delen vormen een bar)
            for(int j=0;j<=3;j++){
               //De waarde (aantal noten) bepalen tussen de [- en ]-tekens
               index1 = nthOccurrence(bars.get(i).toString(), '[', j);
               index2 = nthOccurrence(bars.get(i).toString(), ']', j);
               hulpString = bars.get(i).toString().substring(index1+1,index2);
               aantalNoteset.add(hulpString);
               //System.out.println("nrNoteset: "+hulpString);

               //De noten zelf bepalen (deze komen voor tussen de ]- en [-tekens
               //Opm: Bij het 4e deel kunnen we geen "eindteken" vinden.
               //     Daarom werken we hier met een andere methonde

               if(j<3){ //Voor de eerste 3 delen
                    index1 = nthOccurrence(bars.get(i).toString(), ']', j);
                    index2 = nthOccurrence(bars.get(i).toString(), '[', j+1);
                    hulpString = bars.get(i).toString().substring(index1+1,index2);
                    noteSet.add(hulpString);
               }
               else{    //Voor het laatste deel
                    index1 = nthOccurrence(bars.get(i).toString(), ']', j);
                    index2 = bars.get(i).toString().length();
                    hulpString = bars.get(i).toString().substring(index1+1,index2);
                    noteSet.add(hulpString);
               }            
            }            
        }
        System.out.println("Aantal notesets: " + noteSet.size());
        converToHit();

    }

    ///////////

    public void converToHit(){
        ////////De noteset verder ontleden tot elke actie

       // System.out.println("aantalNoteset size: " + aantalNoteset.size()) ;
       // System.out.println("aantalNoteset.get(j).toString()): " + aantalNoteset.get(0).toString()) ;
        for(int j=0;j<noteSet.size();j++){   //De for lus 24 keer uitvoeren. voor elke noteset
            //System.out.println("\nnoteset: " + j + "   " +noteSet.get(j)) ;

            for(int i=0;i<Integer.parseInt(aantalNoteset.get(j).toString());i++){ //De for lus 4 keer uitvoeren, voor elke actie
               if(i==0){ //Voor het eerste deel te bepalen
                      index2 = DrumLijn.nthOccurrence(noteSet.get(j).toString(), ',', i);
                      hulpString = noteSet.get(j).toString().substring(0,index2);
               }
               else{
                   if(i==Integer.parseInt(aantalNoteset.get(j).toString())-1){ //Voor het laatste deel te bepalen
                      index2 = DrumLijn.nthOccurrence(noteSet.get(j).toString(), ',', i-1);
                      hulpString = noteSet.get(j).toString().substring(index2+1,noteSet.get(j).toString().length());
                   }
                   else{ //Voor de 2 tussenliggende waardes
                       index1 = DrumLijn.nthOccurrence(noteSet.get(j).toString(), ',', i-1);
                       index2 = DrumLijn.nthOccurrence(noteSet.get(j).toString(), ',', i);
                       hulpString = noteSet.get(j).toString().substring(index1+1,index2);
                   }
               }

              hulpInt=0;
              do{ ///////////////Elke slag apart ontleden///////////////////////
                  noteLetter= hulpString.charAt(hulpInt);

                  //System.out.println(noteLetter + " op actie " + i + " in noteset " + j + " bestaande uit een totaal van " + hulpString.length() + " noten, en  " + aantalNoteset.get(j) + " acties in deze bar.") ;

                  hulpInt2 = j%4;
                  //switch (aantal acties in de Noteset
                  switch (Integer.parseInt(aantalNoteset.get(j).toString())){
                    case 1:
                        xPos = 45 + j%4*144;
                        break;
                    case 2:
                        xPos = 45 + j%4*144 + i*72;
                        break;
                    case 3:
                        xPos = 45 + j%4*144 + i*48;
                        break;
                    case 4:
                        xPos = 45 + j%4*144 + i*36;
                        break;
                    case 6:
                        xPos = 45 + j%4*144 + i*24;
                        break;
                    case 8:
                        xPos = 45 + j%4*144 + i*18;
                        break;
                  }
                  yPos = base + (j/4) * 70;
                  note = new Note(noteLetter, xPos, yPos);
                  //repaint();
                  hulpInt++;
              }
              while(hulpInt<(hulpString.length()));
            }
        }
    }

    ///////////

    public int getBPM() {
        return bpm;
    }

    public void setBPM(int bpm) {
        this.bpm = bpm;
    }

    public String getFilename(){
        return filename;
    }

    public void setFilename(String fileLocation, String filename){
        this.fileLocation = fileLocation;
        this.filename=filename;
    }

    //Een bepaald karakter opzoeken in de string, en de positie ervan terugsturen
    public static int nthOccurrence(String str, char c, int n) {
    int pos = str.indexOf(c, 0);
    while (n-- > 0 && pos != -1)
        pos = str.indexOf(c, pos+1);
    return pos;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (note!=null){
          note.teken(g);
        }      
    }

    public void teken(Graphics g) {

    }

}

///////////

class Cursor extends JPanel{
    private int base, cursorXpositie;

    public Cursor(int base) {

        this.base = base;

    }

    public int getcursorXpositie() {
        return cursorXpositie;
    }

    public void setcursorXpositie(int cursorXpositie) {
        this.cursorXpositie = cursorXpositie;
    }


}


/////
class Note extends JPanel{

    private int xPos,base=120,metro;
    private char noteLetter;

    public Note(char noteLetter, int xPos, int yPos) {

        System.out.println("Positie x: " + xPos + " positie y: " + yPos + " noot:  " + noteLetter);
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        
    }

    public void teken(Graphics g) {

         for(int i = 0;i<100;i++){
            System.out.println("test teken van noot, i=" + i);
            //Nieuwe notenbalk tekenen, met 70 px verschil tussen de balken
            g.setColor(Color.BLUE);
            g.fillOval(50, 50, 100, 100);

        }

    }

}

Recommended Answers

All 5 Replies

I would like to draw something on my panel. But I'm not able to draw anything

What method is supposed to do the drawing?
Is that method called with a graphics object for the JPanel that is shown in your GUI?

Can you make a smaller simpler program (SSCCE) that compiles and executes to show your problem?

Hi, thanks for the quick responce!
I don't know if I understand your question correctly, but I guess that is not the problem. When I remove the setLayout rule at rule 55, I'm able to draw on the JPanel. Of course, then my layout isn't optimal. But it proves that it works (kind of..).
Can it be that I'm drawing "underneath" the other panels I'm adding?

EDIT: I'll try to do that as soon as possible! ;)

NormR1, I've made a runnable program from my code.
The only thing that I couldn't fix in a second is to open a file automatically. So you have to select a file with the "open file" button. Sorry.. But it doesn't matter which file you choose, that's set automatically.

What will I see if I compile and execute this code? What is it supposed to do that it is not doing?

Hi,

I've found a workaround for my problem. I have changed my layout so that it's not a problem anymore. So this thread may be closed. But thanks for the help anyway!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.