0

So, my problem here is that I want a JPanel on my JFrame to function as a slideshow where 4 different pictures fade in and fade out. I'm using the Scalr library to resize, everything works except with I use run(); As soon as I use that my window won't open and it get stuck with just the text running through. Is there anyway to make this panel have it's own way? Just sitting in the corner and doing his own thing? A basic explanation would be lovely because I'm very new with Threads and everything around that.

Thank you!

import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JSplitPane;

import java.awt.BorderLayout;
import java.awt.GridBagLayout;

import javax.swing.JPanel;

import java.awt.GridBagConstraints;

import javax.swing.JButton;
import javax.swing.JTextField;

import java.awt.Insets;

import javax.swing.JTextArea;
import javax.swing.JList;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.Dimension;
import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.AbstractAction;

import se.lundell.team.Team;

import javax.swing.ListSelectionModel;
import javax.swing.Action;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;

import org.imgscalr.Scalr;

public class MainWindow {

    private JFrame frame;
    private JTextField textField;
    private final ButtonGroup buttonGroup = new ButtonGroup();
    protected DefaultListModel<Team> teamList;
    private JList list;
    private JTextArea textArea;
    private final Action addTeamAction = new AddTeamAction();
    private final Action removeTeamAction = new RemoveTeamAction();
    private final Action clearListAction = new ClearListAction();
    private final Action generateAction = new GenerateAction();
    public ArrayList<Team> teamA;
    public ArrayList<Team> teamB;

    /**
     * Create the application.
     */
    public MainWindow() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 957, 642);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout(0, 0));

        JSplitPane splitPane = new JSplitPane();
        frame.getContentPane().add(splitPane, BorderLayout.CENTER);

        JPanel leftPanel = new JPanel();
        splitPane.setLeftComponent(leftPanel);
        GridBagLayout gbl_leftPanel = new GridBagLayout();
        gbl_leftPanel.columnWidths = new int[]{0, 0};
        gbl_leftPanel.rowHeights = new int[]{0, 0, 41, 66, 0, 0};
        gbl_leftPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
        gbl_leftPanel.rowWeights = new double[]{1.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
        leftPanel.setLayout(gbl_leftPanel);

        teamList = new DefaultListModel<Team>();

        teamList.addElement(new Team("team1"));
        teamList.addElement(new Team("team2"));
        teamList.addElement(new Team("team3"));
        teamList.addElement(new Team("team4"));


        list = new JList();
        list.setModel(teamList);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        GridBagConstraints gbc_list = new GridBagConstraints();
        gbc_list.insets = new Insets(0, 0, 5, 0);
        gbc_list.fill = GridBagConstraints.BOTH;
        gbc_list.gridx = 0;
        gbc_list.gridy = 0;
        leftPanel.add(list, gbc_list);

        textField = new JTextField();
        GridBagConstraints gbc_textField = new GridBagConstraints();
        gbc_textField.insets = new Insets(0, 0, 5, 0);
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 0;
        gbc_textField.gridy = 1;
        leftPanel.add(textField, gbc_textField);
        textField.setColumns(10);

        JPanel btnPanel = new JPanel();
        GridBagConstraints gbc_btnPanel = new GridBagConstraints();
        gbc_btnPanel.insets = new Insets(0, 0, 5, 0);
        gbc_btnPanel.fill = GridBagConstraints.VERTICAL;
        gbc_btnPanel.gridx = 0;
        gbc_btnPanel.gridy = 2;
        leftPanel.add(btnPanel, gbc_btnPanel);
        btnPanel.setLayout(new GridLayout(0, 3, 0, 0));

        JButton btnAdd = new JButton("Add");
        btnAdd.setAction(addTeamAction);
        buttonGroup.add(btnAdd);
        btnPanel.add(btnAdd);

        JButton btnRemove = new JButton("Remove");
        btnRemove.setAction(removeTeamAction);
        buttonGroup.add(btnRemove);
        btnPanel.add(btnRemove);

        JButton btnClear = new JButton("Clear");
        btnClear.setAction(clearListAction);
        buttonGroup.add(btnClear);
        btnPanel.add(btnClear);

        JPanel generatePanel = new JPanel();
        generatePanel.setPreferredSize(new Dimension(10, 20));
        GridBagConstraints gbc_generatePanel = new GridBagConstraints();
        gbc_generatePanel.fill = GridBagConstraints.BOTH;
        gbc_generatePanel.insets = new Insets(0, 0, 5, 0);
        gbc_generatePanel.gridx = 0;
        gbc_generatePanel.gridy = 3;
        leftPanel.add(generatePanel, gbc_generatePanel);
        generatePanel.setLayout(new GridLayout(1, 0, 0, 0));

        JButton btnGenerate = new JButton("Generate");
        btnGenerate.setAction(generateAction);
        btnGenerate.setFont(new Font("Tahoma", Font.PLAIN, 26));
        generatePanel.add(btnGenerate);

        PictureFrame canvasPanel = new PictureFrame();
        GridBagConstraints gbc_canvasPanel = new GridBagConstraints();
        gbc_canvasPanel.fill = GridBagConstraints.BOTH;
        gbc_canvasPanel.gridx = 0;
        gbc_canvasPanel.gridy = 4;
        leftPanel.add(canvasPanel, gbc_canvasPanel);

        JPanel rightPanel = new JPanel();
        splitPane.setRightComponent(rightPanel);
        rightPanel.setLayout(new BorderLayout(0, 0));

        textArea = new JTextArea();
        textArea.setEditable(false);
        textArea.setAlignmentY(Component.BOTTOM_ALIGNMENT);
        textArea.setAlignmentX(Component.LEFT_ALIGNMENT);
        rightPanel.add(textArea, BorderLayout.CENTER);

        JMenuBar menuBar = new JMenuBar();
        frame.getContentPane().add(menuBar, BorderLayout.NORTH);

        JMenu mnMenu = new JMenu("Menu");
        menuBar.add(mnMenu);

        JMenuItem mntmLoad = new JMenuItem("Load");
        mnMenu.add(mntmLoad);

        JMenuItem mntmSave = new JMenuItem("Save");
        mnMenu.add(mntmSave);

        JMenuItem mntmExit = new JMenuItem("Exit");
        mnMenu.add(mntmExit);

        frame.setVisible(true);
    }

    protected JList getList() {
        return list;
    }

    private class AddTeamAction extends AbstractAction {
        public AddTeamAction() {
            putValue(NAME, "Add");
            putValue(SHORT_DESCRIPTION, "Add team to list.");
        }

        public void actionPerformed(ActionEvent e) {
            if(!textField.getText().isEmpty()) {
                teamList.addElement(new Team(textField.getText()));
                textField.setText("");
            } else {
                JOptionPane.showMessageDialog(null, "You need to enter a name.", "Error!", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    private class RemoveTeamAction extends AbstractAction {
        public RemoveTeamAction() {
            putValue(NAME, "Remove");
            putValue(SHORT_DESCRIPTION, "Remove the selected team.");
        }

        public void actionPerformed(ActionEvent e) {
            int choice = getList().getSelectedIndex();
            teamList.removeElementAt(choice);
        }
    }
    private class ClearListAction extends AbstractAction {
        public ClearListAction() {
            putValue(NAME, "Clear");
            putValue(SHORT_DESCRIPTION, "Clear the list and the tournament window");
        }

        public void actionPerformed(ActionEvent e) {
            teamList.clear();
            textArea.setText("");
            teamA.clear();
            teamB.clear();
        }
    }
    private class GenerateAction extends AbstractAction {
        public GenerateAction() {
            putValue(NAME, "Generate");
            putValue(SHORT_DESCRIPTION, "Generate a new Round Robin tournament.");

            teamA = new ArrayList<Team>();
            teamB = new ArrayList<Team>();
        }

        public void actionPerformed(ActionEvent e) {
            rotateSchedual();
        }

        private void rotateSchedual(){

            if(teamList.getSize() % 2 == 0) {
                start();
            } else {
                teamList.addElement(new Team("Dummy"));
                start();
            }
        }

        protected void start() {
            for(int i = 0; i < teamList.getSize(); i++) {
                teamA.add(teamList.getElementAt(i));
            }

            // Split the arrayList to two and invert.
            splitSchedual();

            int length = teamA.size();
            System.out.println(teamB.size());
            System.out.println(length);

            printSchedual(length);
            //remove index 0 from teamA and add index 0 from teamB first in the list. then add the first team back in again.
            for(int i = 0;i <= (length - 1); i++){
                //copy index 0 and add it to the other array.
                //remove index 0 in both arrays.
                teamA.add(1, teamB.get(0));
                teamB.remove(0);
                teamB.add(teamA.get(length));
                teamA.remove(length);
                printSchedual(length);
            }
        }

        //Splits the array in to two arrays.
        protected void splitSchedual(){
            int length = teamA.size();

            for(int i = (length/2);i < (length);i++){
                teamB.add(teamA.get(i));
            }

            for(int i = (length - 1);i >= (length/2); i--) {
                teamA.remove(i);
            }
        }

        protected void printSchedual(int length){
            int rounds = length;

            for(int i = 0; i < (rounds - 1); i++){
                textArea.append((i+1) + ". " + teamA.get(i).getTeamname() + " - " + teamB.get(i).getTeamname() + "\n");
            }
            textArea.append("-----------------------------\n");
        }
    }

    public class PictureFrame extends JPanel implements Runnable {
        Runnable run;
        Image[] imageArray = new Image[4]; 
        Image resized;

        public PictureFrame() {
            setVisible(true);

            try {
                imageArray[0] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/TrophyTheChampion.gif").getFile()));
                imageArray[1] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/trophy.gif").getFile()));
                imageArray[2] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/trophy1.gif").getFile()));
                imageArray[3] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/nicolas_cage.jpg").getFile()));
            } catch (IOException e) {
                e.printStackTrace();
            }

            resized = Scalr.resize((BufferedImage)imageArray[0], 190, 190);

        }

        @Override
        public void run() {

            System.out.println("körs bara en gång.");

            while(true) {
                System.out.println("This will print, over and over again.");

                for(int i = 0; i < imageArray.length; i++) {
                    resized = Scalr.resize((BufferedImage)imageArray[i], 190, 190);
                    repaint();

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }       
        }

        @Override
        public void paint(Graphics g) {
            g.drawImage(resized, 30, 0, null);

        }
    }   
}
Lundell
  • 109
  • 1
  • 7
  • 1. you have to use Swing Timer instead of Runnable#Thread stopped by THread.Sleep, in Java7 and newer version repaint() could not invoke EventDispatchThread – mKorbel Nov 17 '13 at 16:21
  • 2. use paintComponent instead of paint for Swing JPanel, with 1st code inside super.paintComponent, – mKorbel Nov 17 '13 at 16:22
  • 3. use JLabel.setIcon(myImageStoredInLocalVariable) if aren't any JComponent added to JPanel – mKorbel Nov 17 '13 at 16:23
  • See also this [example](http://stackoverflow.com/a/2234020/230513) using `AlphaComposite`. – trashgod Nov 17 '13 at 16:43

0 Answers0