Changing colors slowly, Java Graphics - java

I have a gradient background and I want, slowly, for it to change colors, basically for it to go through different colors. The color has to blend through all the colors, I do not want it to flick through colors, is this possible? Please enlighten me with a solution, thanks.

Also consider java.awt.image.MemoryImageSource and a javax.swing.Timer, illustrated here and below.

Really too hard to say anything (whatever clever) to my defense, (try & enjoy)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.swing.*;
public class GradientPaintWithSwingTimerAndRunnable extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private Queue<Icon> iconQueue = new LinkedList<Icon>();
private JLabel label = new JLabel();
private Random random = new Random();
private JPanel buttonPanel = new JPanel();
private JPanel labelPanel = new JPanel();
private Timer backTtimer;
private Timer labelTimer;
private JLabel one = new JLabel("one");
private JLabel two = new JLabel("two");
private JLabel three = new JLabel("three");
private final String[] petStrings = {"Bird", "Cat", "Dog",
"Rabbit", "Pig", "Fish", "Horse", "Cow", "Bee", "Skunk"};
private boolean runProcess = true;
private int index = 1;
private int index1 = 1;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GradientPaintWithSwingTimerAndRunnable t = new GradientPaintWithSwingTimerAndRunnable();
}
});
}
public GradientPaintWithSwingTimerAndRunnable() {
iconQueue.add(UIManager.getIcon("OptionPane.errorIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.informationIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.warningIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.questionIcon"));
one.setFont(new Font("Dialog", Font.BOLD, 24));
one.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
two.setFont(new Font("Dialog", Font.BOLD, 24));
two.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
three.setFont(new Font("Dialog", Font.BOLD, 10));
three.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labelPanel.setLayout(new GridLayout(0, 3, 4, 4));
labelPanel.add(one);
labelPanel.add(two);
labelPanel.add(three);
//labelPanel.setBorder(new LineBorder(Color.black, 1));
labelPanel.setOpaque(false);
JButton button0 = createButton();
JButton button1 = createButton();
JButton button2 = createButton();
JButton button3 = createButton();
buttonPanel.setLayout(new GridLayout(0, 4, 4, 4));
buttonPanel.add(button0);
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
//buttonPanel.setBorder(new LineBorder(Color.black, 1));
buttonPanel.setOpaque(false);
label.setLayout(new BorderLayout());
label.add(labelPanel, BorderLayout.NORTH);
label.add(buttonPanel, BorderLayout.SOUTH);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
label.setPreferredSize(new Dimension(d.width / 3, d.height / 3));
add(label, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
startBackground();
startLabel2();
new Thread(this).start();
printWords(); // generating freeze Swing GUI durring EDT
}
private JButton createButton() {
JButton button = new JButton();
button.setBorderPainted(false);
button.setBorder(null);
button.setFocusable(false);
button.setMargin(new Insets(0, 0, 0, 0));
button.setContentAreaFilled(false);
button.setIcon(nextIcon());
button.setRolloverIcon(nextIcon());
button.setPressedIcon(nextIcon());
button.setDisabledIcon(nextIcon());
nextIcon();
return button;
}
private Icon nextIcon() {
Icon icon = iconQueue.peek();
iconQueue.add(iconQueue.remove());
return icon;
}
// Update background at 4/3 Hz
private void startBackground() {
backTtimer = new javax.swing.Timer(750, updateBackground());
backTtimer.start();
backTtimer.setRepeats(true);
}
private Action updateBackground() {
return new AbstractAction("Background action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(getImage()));
}
};
}
// Update Label two at 2 Hz
private void startLabel2() {
labelTimer = new javax.swing.Timer(500, updateLabel2());
labelTimer.start();
labelTimer.setRepeats(true);
}
private Action updateLabel2() {
return new AbstractAction("Label action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
two.setText(petStrings[index]);
index = (index + 1) % petStrings.length;
}
};
}
// Update lable one at 3 Hz
#Override
public void run() {
while (runProcess) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
one.setText(petStrings[index1]);
index1 = (index1 + 1) % petStrings.length;
}
});
try {
Thread.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Note: blocks EDT
private void printWords() {
for (int i = 0; i < petStrings.length; i++) {
String word = petStrings[i].toString();
System.out.println(word);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
three.setText(word);
}
three.setText("<html> Concurency Issues in Swing<br>"
+ " never to use Thread.sleep(int) <br>"
+ " durring EDT, simple to freeze GUI </html>");
}
public BufferedImage getImage() {
int w = label.getWidth();
int h = label.getHeight();
GradientPaint gp = new GradientPaint(0f, 0f, new Color(
127 + random.nextInt(128),
127 + random.nextInt(128),
127 + random.nextInt(128)),
w, w,
new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
g2d.setColor(Color.BLACK);
return bi;
}
}

Related

JButtons keep redrawing

I'm trying to make a goal organizer program and want to be able to zoom in and out with the buttons moving with the border of the rectangle, but when I press the zoom in or out button it leaves the original where it is and creates a new one over it. Also the buttons are shown in the position I coded for, but they also show up at the top of the screen.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Screen extends JPanel implements Runnable{
/**
*
*/
private static final long serialVersionUID = 1L;
Frame frame;
Thread thread = new Thread(this);
public JButton one;
public JButton two;
public JButton zoomIn;
public JButton zoomOut;
public JButton next;
public JButton xv;
int buttonW = 100;
int buttonH = 50;
int zoomLevel = 5;
int fps;
public boolean running = true;
public Screen(Frame frame) {
this.frame = frame;
thread.start();
}
public void run() {
long lastFrame = System.currentTimeMillis();
int frames = 0;
running = true;
while(running){
repaint();
frames++;
if(System.currentTimeMillis() - 1000 >= lastFrame){
fps = frames;
frames = 0;
lastFrame = System.currentTimeMillis();
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void paintComponent(Graphics g){
Color bgc = new Color (192,192,192);
int screenW = this.getWidth();
int screenH = this.getHeight();
int centerH = screenH / 2;
int centerW = screenW / 2;
g.setColor(bgc);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
/*---------------------------button-stuff------------------------------ **/
Icon plus = new ImageIcon("res/buttons/plus.png");
Icon minus = new ImageIcon("res/buttons/minus.png");
/*---------------------------zoom buttons------------------------------**/
zoomOut = new JButton("", minus);
zoomOut.setBounds(screenW - 30, 32, 20, 20);
zoomOut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
buttonH = buttonH-10;
buttonW = buttonW-20;
zoomLevel = zoomLevel-1;
}
});
zoomIn = new JButton("", plus);
zoomIn.setBounds(screenW - 30, 10, 20, 20);
zoomIn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
buttonH = buttonH+10;
buttonW = buttonW+20;
zoomLevel = zoomLevel+1;
}
});
/*------------------------------------Next--------------------------------------------------------**/
next = new JButton("");
next.setBounds(centerW + ((buttonW / 2) - 5), centerH - 5, 10, 10);
next.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
JButton oo = new JButton("new");
oo.setBounds(10,10,10,10);
add(oo);
}
});
xv = new JButton("");
add(xv);
xv.setBounds(centerW -10, centerH - ((buttonH / 2) + 10), 20, 20);
/*------------------------------Add Buttons----------------------------------------------------------**/
add(zoomOut);
add(zoomIn);
add(next);
g.setColor(Color.GREEN);
g.fillRect(centerW - (buttonW / 2), centerH - (buttonH / 2), buttonW, buttonH);
}
}

Why JTextField.setText("String") doesn't work in a DocumentListener?

I have to build a GUI that takes 4 colorable shapes (MyShape class) that are going to be grey in the beginning. Later, writing the RGB values on the three JTextField on the bottom of the GUI i'll be able to set the new color that will paint every picture that I'll click later.
Everything works great except the fact that in the DocumentListener i can't use the setText method or I'll get an IllegalStateException. I'd like to call that method in order to correct a wrong value of an RGB component: for instance, if the user writes 500, the text will automatically set the JTextField to 255.
Here is the code of the full project, so that you can run it (in the code I commented the line right before the method with the problem (I know it's kinda long to read, thank you if you'll help me anyway! :) ):
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.util.Arrays;
import java.util.List;
public class ShapesGUI extends JFrame {
private ShapesPlayGround shapesPlayGround;
private ColorPreview colorPreview;
private RGB rgb;
private List<MyShape> shapeList;
public ShapesGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
Container cnt = getContentPane();
shapesPlayGround = new ShapesPlayGround();
colorPreview = new ColorPreview();
rgb = new RGB();
cnt.add(shapesPlayGround, BorderLayout.CENTER);
cnt.add(colorPreview, BorderLayout.WEST);
cnt.add(rgb, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public void setShapeList(List<MyShape> shapeList) {this.shapeList = shapeList;}
class ShapesPlayGround extends JPanel {
MyShape[] shapes;
public ShapesPlayGround() {
setPreferredSize(new Dimension(800, 450));
setBorder(new TitledBorder("Shapes"));
shapes = new MyShape[4];
shapes[0] = new MyShape(new Rectangle2D.Double(50, 250, 40, 180)); // Rettangolo, basso sinistra
shapes[1] = new MyShape(new Rectangle2D.Double(500, 100, 250, 250)); // Quadrato, estrema destra
shapes[2] = new MyShape(new Ellipse2D.Double(75, 50, 250, 120)); // Ellisse, alto sinistra
shapes[3] = new MyShape(new Ellipse2D.Double(310, 200, 230, 230)); // Cerchio, destra
setShapeList(Arrays.asList(shapes));
addMouseListener(new MyMouseListener());
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for (MyShape shape : shapes) {
g2.setPaint(shape.getColor());
g2.fill(shape.getShape());
g2.setPaint(Color.black);
g2.draw(shape.getShape());
}
}
class MyMouseListener extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
Point p = new Point(e.getX(), e.getY());
if (shapeList != null) {
for (MyShape shape : shapes) {
if (shape.getShape().contains(p)) {
shape.setColor(rgb.getColor());
}
repaint();
}
}
}
}
}
class ColorPreview extends JPanel {
int[] rgbValue = new int[3];
JPanel panel;
Shape preview;
public ColorPreview() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new JLabel(" Preview "));
panel = new JPanel();
panel.setBorder(new TitledBorder("Color"));
add(panel);
}
public void setColor(int[] rgbValue) {this.rgbValue = rgbValue;}
public int[] getColor() {return rgbValue;}
public void paintColor() {
Graphics2D g2 = (Graphics2D)getGraphics();
preview = new Rectangle2D.Double(panel.getX() + 5, panel.getY() + 20, panel.getWidth() - 10, panel.getWidth() - 10);
g2.setPaint(rgb.getColor());
g2.fill(preview);
}
}
class RGB extends JPanel {
private JPanel[] rgbPanel = new JPanel[3];
private String[] panelTitles = {"Red", "Green", "Blue"};
private JTextField[] rgbText = new JTextField[3];
private JTextField[] partialColor = new JTextField[3];
private Shape[] rgbShape;
private int[] rgbValue = new int[3];
private Color color;
public RGB() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
for (int i = 0; i < 3; i++) {
rgbPanel[i] = new JPanel();
rgbPanel[i].setLayout(new GridLayout(1, 2));
rgbPanel[i].setBorder(new TitledBorder(panelTitles[i]));
rgbText[i] = new JTextField();
partialColor[i] = new JTextField();
rgbValue[i] = 0;
rgbText[i].setText("0");
rgbText[i].getDocument().addDocumentListener(new TextChanged(i));
partialColor[i].setBackground(Color.black);
partialColor[i].setEditable(false);
rgbPanel[i].add(rgbText[i]);
rgbPanel[i].add(partialColor[i]);
add(rgbPanel[i]);
}
color = new Color(rgbValue[0], rgbValue[1], rgbValue[2]);
}
public int[] getRgbValue() {return rgbValue;}
public Color getColor() {return color;}
public void setRgbValue(int[] rgbValue) {this.rgbValue = rgbValue;}
public void setColor(Color color) {this.color = color;}
class TextChanged implements DocumentListener {
private int i;
public TextChanged(int i) {this.i = i;}
#Override
public void insertUpdate(DocumentEvent e) {listen(i);}
#Override
public void removeUpdate(DocumentEvent e) {listen(i);}
#Override
public void changedUpdate(DocumentEvent e) {listen(i);}
private int fixValue(int value) {return value < 0 ? 0 : (value > 255 ? 255 : value);}
// HERE'S THE PROBLEM!!!
private void listen(int i) {
try {
rgbValue[i] = fixValue(Integer.parseInt(rgbText[i].getText()));
} catch (NumberFormatException e) {
rgbValue[i] = 0;
}
color = new Color(rgbValue[0], rgbValue[1], rgbValue[2]);
rgb.setColor(color);
colorPreview.paintColor();
try {
rgbText[i].setText("" + rgbValue[i]);
} catch (IllegalStateException e) {
System.out.println("~Shit, Exception");
}
if (i == 0) partialColor[0].setBackground(new Color(rgbValue[0], 0, 0));
else if (i == 1) partialColor[1].setBackground(new Color(0, rgbValue[1], 0));
else if (i == 2) partialColor[2].setBackground(new Color(0, 0, rgbValue[2]));
}
}
}
public static void main(String args[]) {
new ShapesGUI();
}
}
One possible solution is to wrap your change to the text in a Runnable and queue it on the event thread using SwingUtilitiles.invokeLater(yourRunnable), but better perhaps ..... you're trying to correct the input before it is fully registered in the text component. In this situation, don't use a DocumentListener, but rather use a DocumentFilter.
Better still -- use a JSlider or a JSpinner
e.g.,
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.EnumMap;
import java.util.Map;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SpinnerEg extends JPanel {
private Map<RGB, JSlider> sliderMap = new EnumMap<>(RGB.class);
private JPanel displayPanel = new JPanel();
private Color displayPanelColor = new Color(0, 0, 0);
public SpinnerEg() {
displayPanel.setBackground(displayPanelColor);
JPanel sliderPanel = new JPanel(new GridLayout(1, 0));
for (RGB rgb : RGB.values()) {
createRgbSlider(sliderPanel, rgb);
}
displayPanel.setPreferredSize(new Dimension(400, 400));
setLayout(new BorderLayout());
add(displayPanel);
add(sliderPanel, BorderLayout.PAGE_END);
}
private void createRgbSlider(JPanel sliderPanel, final RGB rgb) {
final JSlider slider = new JSlider(0, 255, 0);
slider.setMajorTickSpacing(50);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
sliderMap.put(rgb, slider);
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
int red = sliderMap.get(RGB.RED).getValue();
int green = sliderMap.get(RGB.GREEN).getValue();
int blue = sliderMap.get(RGB.BLUE).getValue();
displayPanelColor = new Color(red, green, blue);
displayPanel.setBackground(displayPanelColor);
}
});
JPanel rgbPanel = new JPanel(new BorderLayout());
rgbPanel.setBorder(BorderFactory.createTitledBorder(rgb.getName()));
rgbPanel.add(slider);
sliderPanel.add(rgbPanel);
}
private static void createAndShowGui() {
SpinnerEg mainPanel = new SpinnerEg();
JFrame frame = new JFrame("SpinnerEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
enum RGB {
RED("Red", Color.red), GREEN("Green", Color.green), BLUE("Blue", Color.blue);
private String name;
private Color color;
private RGB(String name, Color color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public Color getColor() {
return color;
}
}

How can I repaint image after clicking it?

I'm working on a game in which you have to click an object, if you clicked right you get 1 score and so on.
If you miss clicked the object you get -1 score.
Now I would like to repaint the image after clicking it, It now just goes on when clicked, only the score changes.
This is my code:
(Note: I left the imports out, because than it will be a mess in the OP)
public class Gamevenster extends JPanel implements Runnable {
public String Gamestatus = "active";
private Thread thread;
//public Main game;
public int random(int min, int max) {
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
public class TestComponent extends JComponent implements MouseListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public TestComponent() {
this.addMouseListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {
int clickedX = e.getX();
int clickedY = e.getY();
System.out.println("User Clicked: " + clickedX + ", " + clickedY);
}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
}
Random rand = new Random();
private int x = 0;
private int y = 0;
Timer timer = new Timer(850, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
x = rand.nextInt(400);
y = rand.nextInt(330);
repaint();
}
});
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(achtergrond, 0, 0, this.getWidth(), this.getHeight(), null);
//g.drawImage(muisje, 10, 10, null);
g.drawImage(muisje, x, y, 100, 100, this);
}
private static final long serialVersionUID = 1L;
private JLabel scoreLabel = new JLabel("SCORE: " + "0");
private int score = 0;
Image achtergrond, muisje;
//JTextField invoer;
JButton raden;
JButton menu;
JButton restartBtn;
Gamevenster() { // CONSTRUCTOR
timer.start();
setLayout(null);
scoreLabel.setFont(new Font("Open Sans", Font.PLAIN, 30));
scoreLabel.setForeground(Color.WHITE);
scoreLabel.setBounds(20, 455, 200, 100);
add(scoreLabel);
addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
int clickX = (int)p.getX();
int clickY = (int)p.getY();
if(clickX > x && clickX < x + 100 && clickY > y && clickY < y + 100) {
score++;
scoreLabel.setText("SCORE: " + score);
repaint();
}else{
score = Math.max(0, score -1);
scoreLabel.setText("SCORE: " + score);
}
}
});
ImageIcon icon = new ImageIcon(this.getClass().getResource("assets/achtergrondspel.png"));
achtergrond = icon.getImage();
ImageIcon icon2 = new ImageIcon(this.getClass().getResource("assets/muisje.png"));
muisje = icon2.getImage();
//Get the default toolkit
Toolkit toolkit = Toolkit.getDefaultToolkit();
//Load an image for the cursor
Image image = toolkit.getImage("src/assets/hand.png");
//Create the hotspot for the cursor
Point hotSpot = new Point(0,0);
//Create the custom cursor
Cursor cursor = toolkit.createCustomCursor(image, hotSpot, "Hand");
//Use the custom cursor
setCursor(cursor);
// setLayout( null );
// Invoer feld
//invoer = new JTextField(10);
//invoer.setLayout(null);
//invoer.setBounds(150, 474, 290, 60); // Verander positie onder aan scherm is int 1
// Button voor raden
raden = new JButton("Raden");
raden.setLayout(null);
raden.setBounds(10, 474, 130, 60);
raden.setFont(new Font("Dialog", 1, 20));
raden.setForeground(Color.white);
raden.setBackground(new Color(46, 204, 113));
raden.setPreferredSize(new Dimension(130, 60));
// Menu knop
menu = new JButton("Menu");
menu.setLayout(null);
menu.setBounds(450, 474, 130, 60);
menu.setFont(new Font("Dialog", 1, 20));
menu.setForeground(Color.white);
menu.setBackground(new Color(46, 204, 113));
menu.setPreferredSize(new Dimension(130, 60));
// Toevoegen aan screen
//add(invoer);
//add(raden);
add(menu);
menu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String i = menu.getText();
System.out.println("Er is gedrukt! " + i);
}
});
}
public void start(){
thread = new Thread(this,"spelloop");
thread.start();
}
public void run() {
while(Gamestatus=="active"){
System.out.println("Gameloop werkt");
}
}
}

Very slow scrolling in JScrollPane when using per-pixel transparency

I am using per-pixel transparency using AWTUtilities.setWindowOpaque() on JFrame, that contains JScrollPane. When transparency is on, the scrolling in that pane is very slow and laggy, without it is not. Trying this on Windows 7 and JDK 6.
public class MainFrame extends JFrame {
super();
setUndecorated(true);
AWTUtilities.setWindowOpaque(this, false); //this turns JScrollPane inside of this JFrame slow and laggy
}
Have anyone issued this? Thanks!
I can't see any scrolling issue, nor to create testing scenario for code that is based on good Swing rules, this code is quite too hard for processor(s) and GPU, Java6, Win7 64b
from code
import com.sun.awt.AWTUtilities;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.TableModel;
public class ViewPortFlickeringOriginal {
private JFrame frame = new JFrame("Table");
private JViewport viewport = new JViewport();
private Rectangle RECT = new Rectangle();
private Rectangle RECT1 = new Rectangle();
private JTable table = new JTable(50, 3);
private javax.swing.Timer timer;
private int count = 0;
private GradientViewPortOriginal tableViewPort;
private static boolean loggerOpacity;
private JPanel panel = new JPanel();
private static JButton button;
public ViewPortFlickeringOriginal() {
tableViewPort = new GradientViewPortOriginal(table);
viewport = tableViewPort.getViewport();
viewport.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (tableViewPort.bolStart) {
RECT = table.getCellRect(0, 0, true);
RECT1 = table.getCellRect(table.getRowCount() - 1, 0, true);
Rectangle viewRect = viewport.getViewRect();
if (viewRect.intersects(RECT)) {
System.out.println("Visible RECT -> " + RECT);
tableViewPort.paintBackGround(new Color(250, 150, 150));
} else if (viewRect.intersects(RECT1)) {
System.out.println("Visible RECT1 -> " + RECT1);
tableViewPort.paintBackGround(new Color(150, 250, 150));
} else {
System.out.println("Visible RECT1 -> ???? ");
tableViewPort.paintBackGround(new Color(150, 150, 250));
}
}
}
});
frame.add(tableViewPort);
button = new JButton("Change Opacity for Java6 / Win7");
button.setBounds(100, 100, 50, 50);
button.setVisible(true);
panel.add(button);
loggerOpacity = true;
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src == button && loggerOpacity) {
AWTUtilities.setWindowOpacity(frame, 0.80f);
}
}
});
frame.add(panel, BorderLayout.SOUTH);
frame.setPreferredSize(new Dimension(600, 300));
frame.pack();
frame.setLocation(50, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RepaintManager.setCurrentManager(new RepaintManager() {
#Override
public void addDirtyRegion(JComponent c, int x, int y, int w, int h) {
Container con = c.getParent();
while (con instanceof JComponent) {
if (!con.isVisible()) {
return;
}
if (con instanceof GradientViewPortOriginal) {
c = (JComponent) con;
x = 0;
y = 0;
w = con.getWidth();
h = con.getHeight();
}
con = con.getParent();
}
super.addDirtyRegion(c, x, y, w, h);
}
});
frame.setVisible(true);
start();
}
private void start() {
timer = new javax.swing.Timer(100, updateCol());
timer.start();
}
public Action updateCol() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("updating row " + (count + 1));
TableModel model = table.getModel();
int cols = model.getColumnCount();
int row = 0;
for (int j = 0; j < cols; j++) {
row = count;
table.changeSelection(row, 0, false, false);
timer.setDelay(100);
Object value = "row " + (count + 1) + " item " + (j + 1);
model.setValueAt(value, count, j);
}
count++;
if (count >= table.getRowCount()) {
timer.stop();
table.changeSelection(0, 0, false, false);
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
table.clearSelection();
tableViewPort.bolStart = true;
}
});
}
}
};
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ViewPortFlickeringOriginal viewPortFlickering = new ViewPortFlickeringOriginal();
}
});
}
}
class GradientViewPortOriginal extends JScrollPane {
private static final long serialVersionUID = 1L;
private final int h = 50;
private BufferedImage img = null;
private BufferedImage shadow = new BufferedImage(1, h, BufferedImage.TYPE_INT_ARGB);
private JViewport viewPort;
public boolean bolStart = false;
public GradientViewPortOriginal(JComponent com) {
super(com);
viewPort = this.getViewport();
viewPort.setScrollMode(JViewport.BLIT_SCROLL_MODE);
viewPort.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
viewPort.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
paintBackGround(new Color(250, 150, 150));
}
public void paintBackGround(Color g) {
Graphics2D g2 = shadow.createGraphics();
g2.setPaint(g);
g2.fillRect(0, 0, 1, h);
g2.setComposite(AlphaComposite.DstIn);
g2.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 0f), 0, h,
new Color(0.1f, 0.8f, 0.8f, 0.5f)));
g2.fillRect(0, 0, 1, h);
g2.dispose();
}
#Override
public void paint(Graphics g) {
if (img == null || img.getWidth() != getWidth() || img.getHeight() != getHeight()) {
img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2 = img.createGraphics();
super.paint(g2);
Rectangle bounds = getViewport().getVisibleRect();
g2.scale(bounds.getWidth(), -1);
int y = (getColumnHeader() == null) ? 0 : getColumnHeader().getHeight();
g2.drawImage(shadow, bounds.x, -bounds.y - y - h, null);
g2.scale(1, -1);
g2.drawImage(shadow, bounds.x, bounds.y + bounds.height - h + y, null);
g2.dispose();
g.drawImage(img, 0, 0, null);
}
}
but I'm able to demonstrating lazy scrolling for JScrollPane contains others JComponents as is JTable or JList or JTextArea or JTextPane
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.*;
public class ListPanel extends JFrame {
private static final long serialVersionUID = 1L;
public ListPanel() {
setLayout(new GridLayout(0, 2, 10, 10));
DefaultListModel model = new DefaultListModel();
model.addElement(createButtons("one"));
model.addElement(createButtons("two"));
model.addElement(createButtons("three"));
model.addElement(createButtons("four"));
model.addElement(createButtons("five"));
model.addElement(createButtons("six"));
model.addElement(createButtons("seven"));
model.addElement(createButtons("eight"));
model.addElement(createButtons("nine"));
model.addElement(createButtons("ten"));
model.addElement(createButtons("eleven"));
model.addElement(createButtons("twelwe"));
JList list = new JList(model);
list.setCellRenderer(new PanelRenderer());
JScrollPane scroll1 = new JScrollPane(list);
final JScrollBar scrollBar = scroll1.getVerticalScrollBar();
scrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar.getValue());
}
});
add(scroll1);
JScrollPane scroll2 = new JScrollPane(createPanel());
add(scroll2);
final JScrollBar scrollBar1 = scroll2.getVerticalScrollBar();
scrollBar1.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar1.getValue());
}
});
}
public static JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1, 1, 1));
panel.add(createButtons("one"));
panel.add(createButtons("two"));
panel.add(createButtons("three"));
panel.add(createButtons("four"));
panel.add(createButtons("five"));
panel.add(createButtons("six"));
panel.add(createButtons("seven"));
panel.add(createButtons("eight"));
panel.add(createButtons("nine"));
panel.add(createButtons("ten"));
panel.add(createButtons("eleven"));
panel.add(createButtons("twelwe"));
return panel;
}
public static JButton createButtons(String text) {
JButton button = new JButton(text);
return button;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ListPanel frame = new ListPanel();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//frame.pack();
frame.setSize(270, 200);
frame.setVisible(true);
}
});
}
class PanelRenderer implements ListCellRenderer {
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JButton renderer = (JButton) value;
renderer.setBackground(isSelected ? Color.red : list.getBackground());
return renderer;
}
}
}

Java: JSplitPane duplicates top panel's contents to bottom panel when Timer is active

So I have a JSplitPane, and two JPanels - one on top, one on the bottom. In both panels I overrode the paintComponent method and added my own graphics. In the bottom panel, I wanted to add an animation. When the panel does not repaint, it's fine, but as soon as the Timer (javax.swing.Timer) starts to call repaints, the bottom panel mimics the appearance of the top panel and glitches out. The actual animations are not refreshed, but rather it keeps on adding (like a dragged paintbrush instead of a moving object).
Here's the code for the Bottom Panel class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class WaitControls extends JPanel {
private int pos;
public WaitControls(){
setBackground(Color.gray);
pos = 0;
}
public void progress(){
//animation timer:
Timer timer = new Timer(30, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
pos++;
repaint();
}
});
timer.start();
}
#Override
public void paintComponent(Graphics g){
g.fillRect(pos, pos, 10, 20);
}
}
And here's the code for the Splitpane class:
//my classes (imported packages)
import rcc.controls.ControlPanel;
import rcc.controls.InitControls;
import rcc.controls.WaitControls;
import rcc.video.Screen;
import javax.swing.JSplitPane;
public class MainPanel extends JSplitPane{
public RCC rcc;
public Screen screen;
private int height;
public ControlPanel curPanel;
public MainPanel(RCC rcc, Screen screen, int height){
super(JSplitPane.VERTICAL_SPLIT);
this.rcc = rcc;
this.screen = screen;
this.height = height;
setDividerSize(2);
setEnabled(false);
setTopComponent(screen);
setToInitControls();
}
//sets the control panel to init controls ***WORKS FINE***
public void setToInitControls(){
InitControls initCtrls = new InitControls(this);
setBottomComponent(initCtrls);
curPanel = initCtrls;
setDividerLocation(height / 4 * 3);
}
//sets the control panel to wait controls (trying to connect) ***GLITCHES***
public void setToWaitControls(){
WaitControls waitCtrls = new WaitControls();
setBottomComponent(waitCtrls);
curPanel = waitCtrls;
setDividerLocation(height / 4 * 3);
waitCtrls.progress();
}
}
The top panel is a bit complicated. It involves mouse action (including a MouseEntered listener) and animates to interact with user mouse input.
The strange thing is, I have another bottom panel that was swapped out that also uses animations, and a timer, and does not have this glitch.
Any ideas what may have caused this? Thank you for all your help!
I can't imagine how your animations works,
1/ but if animation(s) depends of by any of Listener then Timer must be Timer#restart();
2/ check (example), how to pass addNotify()/removeNotify() for start/stop animatiom(s)
NOTE required fullHD monitor for better output or change code line
for (int iPanels = 0; iPanels < 3; iPanels++) {
to
for (int iPanels = 0; iPanels < 2; iPanels++) {
Example:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class AnimationBackground {
public AnimationBackground() {
Random random = new Random();
JFrame frame = new JFrame("Animation Background");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(new GridLayout(0, 3, 10, 10));
for (int iPanels = 0; iPanels < 3; iPanels++) {
final MyJPanel panel = new MyJPanel();
panel.setBackground(Color.BLACK);
for (int i = 0; i < 50; i++) {
Star star = new Star(new Point(random.nextInt(490), random.nextInt(490)));
star.setColor(new Color(100 + random.nextInt(155), 100 + random.nextInt(155), 100 + random.nextInt(155)));
star.setxIncr(-3 + random.nextInt(7));
star.setyIncr(-3 + random.nextInt(7));
panel.add(star);
}
panel.setLayout(new GridLayout(10, 1));
JLabel label = new JLabel("This is a Starry background.", JLabel.CENTER);
label.setForeground(Color.WHITE);
panel.add(label);
JPanel stopPanel = new JPanel();
stopPanel.setOpaque(false);
stopPanel.add(new JButton(new AbstractAction("Stop this madness!!") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
panel.stopAnimation();
}
}));
panel.add(stopPanel);
JPanel startPanel = new JPanel();
startPanel.setOpaque(false);
startPanel.add(new JButton(new AbstractAction("Start moving...") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
panel.startAnimation();
}
}));
panel.add(startPanel);
frame.add(panel);
}
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
AnimationBackground animationBackground = new AnimationBackground();
}
});
}
class Star extends Polygon {
private static final long serialVersionUID = 1L;
private Point location = null;
private Color color = Color.YELLOW;
private int xIncr, yIncr;
static final int WIDTH = 500, HEIGHT = 500;
Star(Point location) {
int x = location.x;
int y = location.y;
this.location = location;
this.addPoint(x, y + 8);
this.addPoint(x + 8, y + 8);
this.addPoint(x + 11, y);
this.addPoint(x + 14, y + 8);
this.addPoint(x + 22, y + 8);
this.addPoint(x + 17, y + 12);
this.addPoint(x + 21, y + 20);
this.addPoint(x + 11, y + 14);
this.addPoint(x + 3, y + 20);
this.addPoint(x + 6, y + 12);
}
public void setColor(Color color) {
this.color = color;
}
public void move() {
if (location.x < 0 || location.x > WIDTH) {
xIncr = -xIncr;
}
if (location.y < 0 || location.y > WIDTH) {
yIncr = -yIncr;
}
translate(xIncr, yIncr);
location.setLocation(location.x + xIncr, location.y + yIncr);
}
public void setxIncr(int xIncr) {
this.xIncr = xIncr;
}
public void setyIncr(int yIncr) {
this.yIncr = yIncr;
}
public Color getColor() {
return color;
}
}
class MyJPanel extends JPanel {
private static final long serialVersionUID = 1L;
private ArrayList<Star> stars = new ArrayList<Star>();
private Timer timer = new Timer(20, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Star star : stars) {
star.move();
}
repaint();
}
});
public void stopAnimation() {
if (timer.isRunning()) {
timer.stop();
}
}
public void startAnimation() {
if (!timer.isRunning()) {
timer.start();
}
}
#Override
public void addNotify() {
super.addNotify();
timer.start();
}
#Override
public void removeNotify() {
super.removeNotify();
timer.stop();
}
MyJPanel() {
this.setPreferredSize(new Dimension(520, 520));
}
public void add(Star star) {
stars.add(star);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (Star star : stars) {
g.setColor(star.getColor());
g.fillPolygon(star);
}
}
}
}

Categories