JRadioButtons selection doesn't update - java

When I run the program I'm able to select one smiley to be active, and I can change this from the JRadio button choices to different selections and it'd work cause I'm testing it with changing colors.
My issue is that I'm only able to change active panels by descending order. I can't go back to a previous one. When I run the program and select smiley_a, I'm able to change its colors, but when I select smiley_b, smiley_a continues the be the one that's changing. Once I get to A, I can't go back to or C or D, and if I start with B, I can't go back to C or D, only to A, and so forth. I'm able to click, but it doesn't update which frame is active.
#Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("Change Colors")) {
update();
selector();
}
if (action.equals("Face +")) {
System.out.println("work");
//frameAsmiley.setSize(20);
//System.out.println("work");
//frameAsmiley.repaint();
}
if (action.equals("Face -")) {
frameAsmiley.setSize(20);
frameAsmiley.repaint();
}
}
#Override
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
if (source == a) {
smiley_a = true;
update();
}if (source == b) {
smiley_b = true;
update();
}if (source== c) {
smiley_c = true;
update();
}if (source == d) {
smiley_d = true;
update();
}
if (source == glasses_on) {
cube_a.repaint();
}if (source == glasses_off) {
cube_a.repaint();
}if (source== c) {
smiley_c = true;
update();
}if (source == d) {
smiley_d = true;
update();
}
if(e.getStateChange() == ItemEvent.SELECTED){
if (emotions.getSelectedItem().equals("Smile!")) {
}
if (emotions.getSelectedItem().equals("Angry!")) {
}if (emotions.getSelectedItem().equals("Sad!")) {
}if (emotions.getSelectedItem().equals("Shock!")) {
}if (emotions.getSelectedItem().equals("Wink!")) {
}
}
}
class OutputScreen extends JPanel {
OutputScreen() {
setPreferredSize(new Dimension(600, 400));
}
}
This is my main code
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashMap;
import java.util.Map;
import static javax.swing.BorderFactory.createCompoundBorder;
public class SmileyTwo extends JFrame implements ActionListener, ItemListener {
private final int framewidth = 1200, frameheight = 1000;
private final int cubes_width = framewidth / 4 - 10, cubes_height = frameheight / 4 - 10;
JPanel mainpanel, cube_1, cube_2, cube_3, cube_4, control_panel_u, control_panel_d, selectsmiley = new JPanel();
JButton color;
JComboBox emotions;
Smiley frameAsmiley, frameBsmiley, frameCsmiley, frameDsmiley, currentpanel;
ButtonGroup eyesopenorclose, glasses_toggle, glasses_state, smileyselector;
JRadioButton eyes_open, eyes_closed, glasses_on, glasses_off, glasses_dark, glasses_clear, a, b, c, d;
JRadioButton left_eye_closed, right_eye_closed = new JRadioButton();
JLabel emotes, smiley, eyestate, glass_state;
Container screen;
boolean smiley_a = false, smiley_b = false, smiley_c = false, smiley_d = false;
int smiley_int_width = 200, smiley_int_height = 200, smiley_face_x_int = 200, smiley_face_y_int = 100;
int smiley_eyes_w = smiley_int_width / 4, smiley_eyes_h = smiley_int_width / 4;
int smileyCtrPoint_x = smiley_face_x_int + smiley_int_width / 2, smileyCtrPoint_y = smiley_face_y_int + smiley_int_height / 2;
int left_eye_x = smileyCtrPoint_x - 80, left_eye_y = smileyCtrPoint_y - 50;
int right_eye_x = smileyCtrPoint_x + 80, right_eye_y = smileyCtrPoint_y - 50;
public OutputScreen cube_a, cube_b, cube_c, cube_d;
public static void main(String[] args) {
int face = 100;
SmileyTwo frame = new SmileyTwo();
frame.setSize(new Dimension(frame.framewidth, frame.frameheight));
frame.setTitle("SMILEY");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.createGui();
frame.repaint();
frame.setVisible(true);
}
public void controlBox() {
JPanel glasses = new JPanel();
JPanel emojis = new JPanel();
JPanel expressions = new JPanel();
JPanel eyes_choices = new JPanel();
JPanel eyepanel = new JPanel();
JPanel glasspanel = new JPanel();
JPanel selectsmiley = new JPanel();
control_panel_u = new JPanel();
control_panel_d = new JPanel();
smileyselector = new ButtonGroup();
eyes_open = new JRadioButton();
eyes_closed = new JRadioButton();
glasses_on = new JRadioButton();
glasses_off = new JRadioButton();
glasses_dark = new JRadioButton();
glasses_clear = new JRadioButton();
left_eye_closed = new JRadioButton();
right_eye_closed = new JRadioButton();
//
JLabel smiley = new JLabel();
smiley.setText("TOGGLE SMILEY BOX");
a = new JRadioButton();
b = new JRadioButton();
c = new JRadioButton();
d = new JRadioButton();
a.addItemListener(this);
b.addItemListener(this);
c.addItemListener(this);
d.addItemListener(this);
JPanel smileyoptions = new JPanel();
JButton color = new JButton("Change Colors");
color.addActionListener(this);
emotes = new JLabel();
emotes.setText("SELECT EMOJI");
emotes.setHorizontalAlignment(JLabel.CENTER);
emotions = new JComboBox();
emotions.addItem("Smile!");
emotions.addItem("Wink!");
emotions.addItem("Shock!");
emotions.addItem("Angry!");
emotions.addItem("Sad!");
emotions.setSize(30, 10);
emotions.addItemListener(this);
emojis.add(emotions);
emojis.add(color);
expressions.add(emotes);
expressions.add(emojis);
expressions.setLayout(new GridLayout(2, 1));
//
eyestate = new JLabel("EYE OPTIONS");
ButtonGroup eyesopenorclose = new ButtonGroup();
eyes_choices.setLayout(new GridLayout(2, 2));
eyes_choices.add(eyes_open);
eyes_choices.add(left_eye_closed);
eyes_choices.add(eyes_closed);
eyes_choices.add(right_eye_closed);
eyepanel.add(eyestate);
eyepanel.add(eyes_choices);
eyes_open.setText("open both eyes");
eyes_closed.setText("close both eyes");
left_eye_closed.setText("close right eye");
right_eye_closed.setText("close left eye");
eyesopenorclose.add(eyes_open);
eyesopenorclose.add(eyes_closed);
eyesopenorclose.add(left_eye_closed);
eyesopenorclose.add(right_eye_closed);
eyepanel.add(eyestate);
eyestate.setHorizontalAlignment(JLabel.CENTER);
eyepanel.add(eyes_choices);
eyepanel.setLayout(new GridLayout(2, 1));
//
glass_state = new JLabel("GLASSES OPTIONS");
ButtonGroup glasses_toggle = new ButtonGroup();
ButtonGroup glasses_state = new ButtonGroup();
glasses_on.setText("glasses on");
glasses_off.setText("glasses off");
glasses_dark.setText("dark shades");
glasses_clear.setText("clear glasses");
glasses_on.addItemListener(this);
glasses_off.addItemListener(this);
glasses_dark.addItemListener(this);
glasses_clear.addItemListener(this);
glasses_toggle.add(glasses_off);
glasses_toggle.add(glasses_on);
glasses_state.add(glasses_dark);
glasses_state.add(glasses_clear);
GridLayout forglass = new GridLayout(2, 2);
glasses.setLayout(new GridLayout(2, 2));
glasses.setBackground(Color.WHITE);
glasses.add(glasses_on);
glasses.add(glasses_dark);
glasses.add(glasses_off);
glasses.add(glasses_clear);
glasspanel.add(glass_state);
glasspanel.add(glasses);
glass_state.setHorizontalAlignment(JLabel.CENTER);
glasspanel.setLayout(new GridLayout(2, 1));
//
smileyselector.add(a);
smileyselector.add(b);
smileyselector.add(c);
smileyselector.add(d);
a.setText("Smiley A");
b.setText("Smiley B");
c.setText("Smiley C");
d.setText("Smiley D");
smileyoptions.add(a);
smileyoptions.add(b);
smileyoptions.add(c);
smileyoptions.add(d);
selectsmiley.add(smiley);
selectsmiley.add(smileyoptions);
smiley.setHorizontalAlignment(JLabel.CENTER);
selectsmiley.setLayout(new GridLayout(2, 1));
//
control_panel_u.setLayout(new FlowLayout());
control_panel_u.add(selectsmiley);
control_panel_u.add(expressions);
control_panel_u.add(glasspanel);
control_panel_u.add(eyepanel);
control_panel_u.setBorder(BorderFactory.createLineBorder(Color.BLACK));
glasses.setBorder(BorderFactory.createLineBorder(Color.BLACK));
eyes_choices.setBorder(BorderFactory.createLineBorder(Color.BLACK));
emojis.setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
public void createGui() {
controlBox();
selector();
Smiley frameAsmiley = new Smiley(150, 100, 400, 400, "shock");
Smiley frameBsmiley = new Smiley(150, 100, 400, 400, "frown");
Smiley frameCsmiley = new Smiley(150, 100, 400, 400,"smile");
Smiley frameDsmiley = new Smiley(150, 100, 400, 400, "wink");
currentpanel = frameAsmiley;
screen = getContentPane();
mainpanel = new JPanel();
JPanel cubepanels = new JPanel();
cube_1 = new JPanel();
cube_2 = new JPanel();
cube_3 = new JPanel();
cube_4 = new JPanel();
cube_a = new OutputScreen();
cube_b = new OutputScreen();
cube_c = new OutputScreen();
cube_d = new OutputScreen();
cube_1.setSize(cubes_width, cubes_height);
cube_2.setSize(cubes_width, cubes_height);
cube_3.setSize(cubes_width, cubes_height);
cube_4.setSize(cubes_width, cubes_height);
cube_a.setSize(cubes_width - 5, cubes_height - 50);
cube_b.setSize(cubes_width - 5, cubes_height);
cube_c.setSize(cubes_width - 5, cubes_height);
cube_d.setSize(cubes_width - 5, cubes_height);
mainpanel.setBackground(Color.WHITE);
cube_1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
cube_2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
cube_3.setBorder(BorderFactory.createLineBorder(Color.BLACK));
cube_4.setBorder(BorderFactory.createLineBorder(Color.BLACK));
cubepanels.add(cube_1, BorderLayout.NORTH);
cubepanels.add(cube_2, BorderLayout.SOUTH);
cubepanels.add(cube_3, BorderLayout.EAST);
cubepanels.add(cube_4, BorderLayout.WEST);
cubepanels.setLayout(new GridLayout(2, 2));
mainpanel.add(cubepanels, BorderLayout.NORTH);
mainpanel.add(control_panel_u, BorderLayout.SOUTH);
cube_a.setBackground(Color.WHITE);
frameAsmiley.setPreferredSize(new Dimension(600, 500));
frameBsmiley.setPreferredSize(new Dimension(600, 500));
frameCsmiley.setPreferredSize(new Dimension(600, 500));
frameDsmiley.setPreferredSize(new Dimension(600, 500));
//
cube_a.add(frameAsmiley, BorderLayout.CENTER);
cube_1.add(cube_a, BorderLayout.CENTER);
cube_1.setLayout(new BoxLayout(cube_1, BoxLayout.Y_AXIS));
frameAsmiley.setBackground(Color.WHITE);
//
cube_b.add(frameBsmiley, BorderLayout.CENTER);
cube_2.add(cube_b, BorderLayout.CENTER);
cube_2.setLayout(new BoxLayout(cube_2, BoxLayout.Y_AXIS));
frameBsmiley.setBackground(Color.WHITE);
//
cube_c.add(frameCsmiley, BorderLayout.CENTER);
cube_3.add(cube_c, BorderLayout.CENTER);
cube_3.setLayout(new BoxLayout(cube_3, BoxLayout.Y_AXIS));
frameCsmiley.setBackground(Color.WHITE);
//
cube_d.add(frameDsmiley, BorderLayout.CENTER);
cube_4.add(cube_d, BorderLayout.CENTER);
cube_4.setLayout(new BoxLayout(cube_4, BoxLayout.Y_AXIS));
frameDsmiley.setBackground(Color.WHITE);
//
screen.add(mainpanel);
}
public void selector() {
if (smiley_a == true) {
smiley_b = false;
smiley_c = false;
smiley_d = false;
cube_a.repaint();
} else if (smiley_b == true) {
smiley_a = false;
smiley_c = false;
smiley_d = false;
cube_b.repaint();
} else if (smiley_c == true) {
smiley_a = false;
smiley_b = false;
smiley_d = false;
cube_c.repaint();
} else if (smiley_d == true) {
smiley_a = false;
smiley_b = false;
smiley_c = false;
cube_d.repaint();
}
}
public void update() {
if (smiley_a == true) {
smiley_b = false;
smiley_c = false;
smiley_d = false;
} else if (smiley_b == true) {
smiley_a = false;
smiley_c = false;
smiley_d = false;
} else if (smiley_c == true) {
smiley_a = false;
smiley_b = false;
smiley_d = false;
} else if (smiley_d == true) {
smiley_a = false;
smiley_b = false;
smiley_c = false;
}
}
#Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("Change Colors")) {
update();
selector();
}
if (action.equals("Face +")) {
System.out.println("work");
frameAsmiley.setSize(20);
//System.out.println("work");
frameAsmiley.repaint();
}
if (action.equals("Face -")) {
frameAsmiley.setSize(20);
frameAsmiley.repaint();
}
}
#Override
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
if (source == a) {
smiley_a = true;
update();
}if (source == b) {
smiley_b = true;
update();
}if (source== c) {
smiley_c = true;
update();
}if (source == d) {
smiley_d = true;
update();
}
if (source == glasses_on) {
cube_a.repaint();
}if (source == glasses_off) {
cube_a.repaint();
}if (source== c) {
smiley_c = true;
update();
}if (source == d) {
smiley_d = true;
update();
}
if(e.getStateChange() == ItemEvent.SELECTED){
if (emotions.getSelectedItem().equals("Smile!")) {
}
if (emotions.getSelectedItem().equals("Angry!")) {
}if (emotions.getSelectedItem().equals("Sad!")) {
}if (emotions.getSelectedItem().equals("Shock!")) {
}if (emotions.getSelectedItem().equals("Wink!")) {
}
}
}
class OutputScreen extends JPanel {
OutputScreen() {
setPreferredSize(new Dimension(600, 400));
}
}
}
this is the custom class
import javax.swing.*;
import java.awt.*;
import java.lang.Object.*;
import java.util.HashSet;
public class Smiley extends JPanel {
public Smiley(int x, int y, int width, int height, String mood) {
this.x = x - 20;
this.y = y - 70;
this.width = width - 100;
this.height = height - 100;
this.mood = mood;
}
public Color randomColor() {
int R = (int) (Math.random() * 255);
int G = (int) (Math.random() * 255);
int B = (int) (Math.random() * 255);
int A = (int) (Math.random() * 3);
Color randomColor = new Color(A, R, G, B);
return randomColor;
}
public int x, y, width, height;
String mood;
HashSet specs;
public int geteyeheight() {
int eyeHeight = height / 5;
return eyeHeight;
}
public String currentlook() {
String currentlook = mood;
return currentlook;
}
public int geteyewidth() {
int eyeWidth = width / 5;
return eyeWidth;
}
public int getlefteyeX() {
int centerPointX = (x + width) / 2;
int leftEyeX = centerPointX - 40;
return leftEyeX;
}
public int getlefteyeY() {
int centerPointY = (y + height) / 2;
int leftEyeY = centerPointY - 50;
return leftEyeY;
}
public int getrighteyeX() {
int centerPointX = (x + width) / 2;
int rightEyeX = centerPointX + 110;
return rightEyeX;
}
public int getrighteyeY() {
int centerPointY = (y + height) / 2;
int rightEyeY = centerPointY - 50;
return rightEyeY;
}
public int getsmileY() {
int centerPointY = (y + height) / 2;
int smileYint = centerPointY + 20;
return smileYint;
}
public int getsmileX() {
int centerPointX = (x + width) / 2;
int smileXint = centerPointX - 10;
return smileXint;
}
public int getsmilewidth() {
int smilewidth = width / 2;
return smilewidth;
}
public int getsmileheight() {
int smileheight = height / 3;
return smileheight;
}
public void setSize(int size){
height+=size;
width+=size;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(randomColor());
g2d.fillOval(x, y, width, height);
g2d.setColor(randomColor());
if (currentlook().equals("smile")) {
DrawSmile(g);
}
else if(currentlook().equals("frown")){
DrawFrown(g);
}else if(currentlook().equals("angry")){
DrawAngry(g);
}else if(currentlook().equals("wink")){
DrawWink(g);
}else if(currentlook().equals("shock")){
DrawShock(g);
}
}
//INDIVIDUAL FACIAL FEATURES
public void rightEye(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.fillOval(getrighteyeX(), getrighteyeY(), geteyewidth(), geteyeheight());
}
public void leftEye(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.fillOval(getlefteyeX(), getlefteyeY(), geteyewidth(), geteyeheight());
}
public void leftEyeAngry(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawLine(getlefteyeX() + 20, getlefteyeY(), getlefteyeX() + 50, getrighteyeY() + 30);
g2d.fillOval(getlefteyeX() + 15, getlefteyeY() + 25, 30, 30);
}
public void rightEyeAngry(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawLine(getrighteyeX() + 30, getrighteyeY(), getrighteyeX(), getrighteyeY() + 30);
g2d.fillOval(getlefteyeX() + 155, getlefteyeY() + 25, 30, 30);
}
public void CloseLeftEye(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(5));
g2d.drawArc(getlefteyeX(), getlefteyeY(), geteyewidth(), geteyeheight(), 0, -180);
}
public void CloseRightEye(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(5));
g2d.drawArc(getrighteyeX(), getrighteyeY(), geteyewidth(), geteyeheight(), 0, -180);
}
public void lipSmile(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(10));
g2d.drawArc(getsmileX(), getsmileY(), getsmilewidth(), getsmileheight(), 0, -180);
}
public void lipFrown(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(10));
g2d.drawArc(getsmileX(), getsmileY() + 30, getsmilewidth(), getsmileheight(), 0, +180);
}
public void winkEye(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawArc(getrighteyeX() - 60, getlefteyeY(), 150, 250, 90, 45);
g2d.drawArc(getrighteyeX() - 90, getlefteyeY() + 30, 150, 200, 60, 45);
}
public void narrowEye(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.fillOval(getlefteyeX() + 20, getlefteyeY(), geteyewidth() - 20, geteyeheight() + 30);
}
public void smallerSmile(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.fillArc(getsmileX() + 30, getsmileY() + 15, getsmilewidth() / 2, getsmileheight(), 0, -180);
}
//EXPRESSIONS
public void DrawSmile(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
rightEye(g);
leftEye(g);
lipSmile(g);
}
public void DrawFrown(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
rightEye(g);
leftEye(g);
lipFrown(g);
}
public void DrawAngry(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(15));
leftEyeAngry(g);
rightEyeAngry(g);
lipFrown(g);
}
public void DrawWink(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(15));
winkEye(g);
narrowEye(g);
smallerSmile(g);
}
public void Glasses(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.drawOval(getlefteyeX() - 20, getlefteyeY() - 20, geteyewidth() + 40, geteyeheight() + 40);
g2d.drawOval(getrighteyeX() - 20, getrighteyeY() - 20, geteyewidth() + 40, geteyeheight() + 40);
g2d.drawArc(getlefteyeX() + 80, getlefteyeY() + 20, 50, 20, 0, 180);
}
public void glassesDark(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillOval(getlefteyeX() - 20, getlefteyeY() - 20, geteyewidth() + 40, geteyeheight() + 40);
g2d.fillOval(getrighteyeX() - 20, getrighteyeY() - 20, geteyewidth() + 40, geteyeheight() + 40);
g2d.drawArc(getlefteyeX() + 70, getlefteyeY() + 20, 70, 20, 0, 180);
}
public void DrawShock(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(15));
g2d.drawLine(getlefteyeX() - 10, getlefteyeY(), getlefteyeX() + 40, getrighteyeY() - 20);
g2d.drawLine(170 + getlefteyeX() + 40, getlefteyeY(), 170 + getlefteyeX() - 10, getrighteyeY() - 20);
g2d.fillOval(getrighteyeX() - 20, getrighteyeY(), geteyewidth() + 20, geteyeheight() + 20);
g2d.fillOval(getlefteyeX(), getlefteyeY(), geteyewidth() + 20, geteyeheight() + 20);
g2d.fillOval(getsmileX() + 40, getsmileY() + 25, geteyewidth() + 20, geteyeheight() + 30);
}
}

Related

java- repaint() method is misbehaving?

I am working on a Music Player
I am using a JSlider as seek bar and using a JLabel to draw text on screen, such as song name.
I am new to Graphics2D
Here's the minimized code:
public class JSliderDemo extends JFrame
{
JLabel label;
JSlider seek = new JSlider();
int y = 10;
public JSliderDemo()
{
setSize(400, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createWindow();
setVisible(true);
startThread();
}
public void createWindow()
{
JPanel panel = new JPanel(null);
panel.setOpaque(true);
panel.setBackground(Color.BLUE);
label = new Component();
label.setSize(400, 400);
label.setLocation(0, 0);
createSlider();
panel.add(seek);
panel.add(label);
add(panel);
}
protected void createSlider()
{
seek.setUI(new SeekBar(seek, 300, 10, new Dimension(20, 20), 5,
Color.DARK_GRAY, Color.RED, Color.RED));
seek.setOrientation(JProgressBar.HORIZONTAL);
seek.setOpaque(false);
seek.setLocation(10, 50);
seek.setSize(300, 20);
seek.setMajorTickSpacing(0);
seek.setMinorTickSpacing(0);
seek.setMinimum(0);
seek.setMaximum(1000);
}
protected void startThread()
{
Thread thread = new Thread(new Runnable(){
#Override
public void run()
{
try
{
while(true)
{
if(y == label.getHeight()){y = 1;}
label.repaint();
y += 1;
Thread.sleep(100);
}
}
catch(Exception ex){}
}
});
thread.start();
}
protected class Component extends JLabel
{
#Override
public void paintComponent(Graphics g)
{
Graphics2D gr = (Graphics2D) g;
gr.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gr.setColor(Color.RED);
gr.setFont(new Font("Calibri", Font.PLAIN, 16));
gr.drawString("Slider", 50, y);
}
}
public static void main(String[] args)
{
new JSliderDemo();
}
}
The Custom Slider UI class prints a line each time the JSlider is repainted.
Through this, I was able to find out that, when I call repaint() for JLabel it automatically repaints JSlider with it even though JSlider is not included in JLabel.
Output :
Slider re-painted
Slider re-painted
Slider re-painted
Slider re-painted
Slider re-painted
Slider re-painted.........
Now if I remove label.repaint() from the Thread, then the JSlider is not re-painted.
Output:
Slider re-painted
Slider re-painted
Is the repaint() method supposed to work like this?
Here's the Custom Slider UI class :
package jsliderdemo;
import java.awt.*;
import javax.swing.*;
import java.awt.geom.RoundRectangle2D;
import javax.swing.plaf.basic.BasicSliderUI;
public class SeekBar extends BasicSliderUI
{
private int TRACK_ARC = 5;
private int TRACK_WIDTH = 8;
private int TRACK_HEIGHT = 8;
private Color backGround = Color.GRAY;
private Color trackColor = Color.RED;
private Color thumbColor = Color.WHITE;
private Dimension THUMB_SIZE = new Dimension(20, 20);
private final RoundRectangle2D.Float trackShape = new RoundRectangle2D.Float();
public SeekBar(final JSlider b, int width, int height, Dimension thumbSize, int arc,
Color backGround, Color trackColor, Color thumbColor)
{
super(b);
this.TRACK_ARC = arc;
this.TRACK_WIDTH = width;
this.TRACK_HEIGHT = height;
this.THUMB_SIZE = thumbSize;
this.backGround = backGround;
this.trackColor = trackColor;
this.thumbColor = thumbColor;
}
#Override
protected void calculateTrackRect()
{
super.calculateTrackRect();
if (isHorizontal())
{
trackRect.y = trackRect.y + (trackRect.height - TRACK_HEIGHT) / 2;
trackRect.height = TRACK_HEIGHT;
}
else
{
trackRect.x = trackRect.x + (trackRect.width - TRACK_WIDTH) / 2;
trackRect.width = TRACK_WIDTH;
}
trackShape.setRoundRect(trackRect.x, trackRect.y, trackRect.width, trackRect.height, TRACK_ARC, TRACK_ARC);
}
#Override
protected void calculateThumbLocation()
{
super.calculateThumbLocation();
if (isHorizontal())
{
thumbRect.y = trackRect.y + (trackRect.height - thumbRect.height) / 2;
}
else
{
thumbRect.x = trackRect.x + (trackRect.width - thumbRect.width) / 2;
}
}
#Override
protected Dimension getThumbSize()
{
return THUMB_SIZE;
}
private boolean isHorizontal()
{
return slider.getOrientation() == JSlider.HORIZONTAL;
}
#Override
public void paint(final Graphics g, final JComponent c)
{
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
super.paint(g, c);
}
#Override
public void paintTrack(final Graphics g)
{
System.out.println("Slider re-painted");
Graphics2D g2 = (Graphics2D) g;
Shape clip = g2.getClip();
boolean horizontal = isHorizontal();
boolean inverted = slider.getInverted();
// Paint shadow.
//g2.setColor(new Color(170, 170 ,170));
//g2.fill(trackShape);
// Paint track background.
g2.setColor(backGround);
g2.setClip(trackShape);
trackShape.y += 1;
g2.fill(trackShape);
trackShape.y = trackRect.y;
g2.setClip(clip);
// Paint selected track.
if (horizontal)
{
boolean ltr = slider.getComponentOrientation().isLeftToRight();
if (ltr) inverted = !inverted;
int thumbPos = thumbRect.x + thumbRect.width / 2;
if (inverted)
{
g2.clipRect(0, 0, thumbPos, slider.getHeight());
}
else
{
g2.clipRect(thumbPos, 0, slider.getWidth() - thumbPos, slider.getHeight());
}
}
else
{
int thumbPos = thumbRect.y + thumbRect.height / 2;
if (inverted)
{
g2.clipRect(0, 0, slider.getHeight(), thumbPos);
}
else
{
g2.clipRect(0, thumbPos, slider.getWidth(), slider.getHeight() - thumbPos);
}
}
g2.setColor(trackColor);
g2.fill(trackShape);
g2.setClip(clip);
}
#Override
public void paintThumb(final Graphics g)
{
g.setColor(thumbColor);
g.fillOval(thumbRect.x, thumbRect.y, thumbRect.width, thumbRect.height);
}
#Override
public void paintFocus(final Graphics g) {}
}

Painting the applet only one time

I am working on a Main Menu for a game and whenever the applet starts running it draws the applet 4 times before starting the program itself it keeps repainting it i added textures to the program so i don't know whats the problem
public class MainMenu extends Applet implements MouseListener, Runnable {
int xpos;
int ypos;
private Image menu = null;
private Image play = null;
private Image exit = null;
int rect1xco, rect1yco, rect1width, rect1height;
int rect2xco, rect2yco, rect2width, rect2height;
boolean mouseEntered;
boolean rect1Clicked;
boolean rect2Clicked;
public void init() {
rect1xco = 590;
rect1yco = 300;
rect1width = 150;
rect1height = 70;
rect2xco = 590;
rect2yco = 400;
rect2width = 150;
rect2height = 70;
addMouseListener(this);
}
public void paint(Graphics g) {
this.setSize(1350, 650);
if (menu == null)
menu = getImage("menu.JPG");
if (play == null)
play = getImage("Button.png");
if (exit == null)
exit = getImage("Button.png");
g.drawImage(menu, 0, 0, getWidth(), getHeight(), this);
g.drawImage(play, 590, 300, 150, 70, this);
g.drawImage(exit, 590, 400, 150, 70, this);
Font Blockt = new Font("INFECTED", Font.ITALIC, 200);
g.setFont(Blockt);
g.setColor(Color.yellow);
g.drawString("DX BALL", 360, 200);
g.getFontMetrics();
Font DIGITAL = new Font("Blockt", Font.ITALIC, 30);
g.setFont(DIGITAL);
g.setColor(Color.black);
g.drawString("Play", 635, 340);
g.drawString("Exit", 635, 440);
if (rect1Clicked) {
}
if (rect2Clicked) {
System.exit(1);
}
}
public void mousePressed(MouseEvent me) {
if (rect1Clicked == true) {
repaint();
play = getImage("ButtonClicked.png");
}
if (rect2Clicked == true) {
repaint();
exit = getImage("ButtonClicked.png");
}
}
public void mouseClicked(MouseEvent me) {
xpos = me.getX();
ypos = me.getY();
rect1Clicked = false;
if (xpos > rect1xco && xpos < rect1xco + rect1width && ypos > rect1yco
&& ypos < rect1yco + rect1height) {
rect1Clicked = true;
System.out.println("Start button pressed"); // start the game
} else
rect1Clicked = false;
if (xpos > rect2xco && xpos < rect2xco + rect1width && ypos > rect2yco
&& ypos < rect2yco + rect2height)
rect2Clicked = true;
else
rect2Clicked = false;
}
public void mouseReleased(MouseEvent me) {
play = getImage("Button.png");
exit = getImage("Button.png");
repaint();
}
public void mouseEntered(MouseEvent me) {
mouseEntered = true;
}
public void mouseExited(MouseEvent me) {
mouseEntered = false;
}

Custom Scrollbar in JScrollpane//Java Swing

I've made my own ScrollbarUI and it works perfectly with JScrollbar. The problem is that I've got to connect this scrollbar with a JPanel to scroll it. I've already tried to use the JScrollPane but when I try to approach the vertical Scrollbar it just won'T respond. I've tried to change some easy things like the cursor, width, height, background to test if the UI is the problem but that didn't work either.
JPanel panel_1 = new JPanel();
JScrollPane scrollpane = new JScrollPane(panel_1);
scrollpane.setBorder(null);
scrollpane.getVerticalScrollBar().setUI(new MyScrollbarUI());
JTextArea txtrLorem = new JTextArea();
txtrLorem.setPreferredSize(new Dimension(400, 1500));
txtrLorem.setMaximumSize(new Dimension(400, 2147483647));
txtrLorem.setText("Lorem ipsum...");
panel_1.add(txtrLorem);
scrollpane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollpane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
GridBagConstraints gbc_panel_1 = new GridBagConstraints();
gbc_panel_1.gridwidth = 5;
gbc_panel_1.insets = new Insets(0, 0, 0, 5);
gbc_panel_1.fill = GridBagConstraints.BOTH;
gbc_panel_1.gridx = 1;
gbc_panel_1.gridy = 4;
add(scrollpane, gbc_panel_1);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setPreferredSize(new Dimension(20, 96));
scrollBar.setMinimumSize(new Dimension(20, 5));
scrollBar.setMaximumSize(new Dimension(20, 32767));
scrollBar.setUI(new MyScrollbarUI());
GridBagConstraints gbc_scrollBar = new GridBagConstraints();
gbc_scrollBar.fill = GridBagConstraints.VERTICAL;
gbc_scrollBar.insets = new Insets(0, 0, 0, 5);
gbc_scrollBar.gridx = 6;
gbc_scrollBar.gridy = 4;
add(scrollBar, gbc_scrollBar);
the JScrollBar has the right design, but the Scrollbar of the JScrollPane hasn't.
Here is the UI:
public class MyScrollbarUI extends BasicScrollBarUI {
#Override
protected JButton createDecreaseButton(int orientation) {
JButton btnL = new JButton("");
btnL.setPressedIcon(new ImageIcon(KFO_baender_bracketsetz_einzel.class.getResource("/gui/icons/top_active.png")));
btnL.setBorderPainted(false);
btnL.setIcon(new ImageIcon(KFO_baender_bracketsetz_einzel.class.getResource("/gui/icons/top_on.png")));
btnL.setRolloverIcon(new ImageIcon(KFO_baender_bracketsetz_einzel.class.getResource("/gui/icons/top.png")));
btnL.setRolloverEnabled(true);
return btnL;
}
#Override
protected JButton createIncreaseButton(int orientation) {
JButton btnL = new JButton("");
btnL.setPressedIcon(new ImageIcon(KFO_baender_bracketsetz_einzel.class.getResource("/gui/icons/down_active.png")));
btnL.setBorderPainted(false);
btnL.setIcon(new ImageIcon(KFO_baender_bracketsetz_einzel.class.getResource("/gui/icons/down_on.png")));
btnL.setRolloverIcon(new ImageIcon(KFO_baender_bracketsetz_einzel.class.getResource("/gui/icons/down.png")));
btnL.setRolloverEnabled(true);
return btnL;
}
#Override
protected void paintDecreaseHighlight(Graphics g)
{
Insets insets = scrollbar.getInsets();
Rectangle thumbR = getThumbBounds();
g.setColor(new Color(137,144,144));
if (scrollbar.getOrientation() == JScrollBar.VERTICAL) {
int x = insets.left+decrButton.getWidth()/2-2;
int y = decrButton.getY() + decrButton.getHeight();
int w = 4;
int h = thumbR.y - y;
g.fillRect(x, y, w, h);
}
else {
int x, w;
if (scrollbar.getComponentOrientation().isLeftToRight()) {
x = decrButton.getX() + decrButton.getWidth();
w = thumbR.x - x;
} else {
x = thumbR.x + thumbR.width;
w = decrButton.getX() - x;
}
int y = insets.top;
int h = scrollbar.getHeight() - (insets.top + insets.bottom);
g.fillRect(x, y, w, h);
}
}
#Override
protected void paintIncreaseHighlight(Graphics g) {
Insets insets = scrollbar.getInsets();
Rectangle thumbR = getThumbBounds();
g.setColor(new Color(202,207,203));
if (scrollbar.getOrientation() == JScrollBar.VERTICAL) {
int x = insets.left+decrButton.getWidth()/2-2;
int y = thumbR.y;
int w = 4;
int h = incrButton.getY() - y;
g.fillRect(x, y, w, h);
}
}
#Override
protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds)
{
g.setColor(Color.WHITE);
g.fillRect(trackBounds.x, trackBounds.y, trackBounds.width, trackBounds.height);
paintDecreaseHighlight(g);
paintIncreaseHighlight(g);
}
#Override
protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds)
{
if(thumbBounds.isEmpty() || !scrollbar.isEnabled()) {
return;
}
int w = 16;
int h = 16;
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.translate(thumbBounds.x, thumbBounds.y);
GradientPaint gr = new GradientPaint(2, 0, new Color(158,161,162), 18, 16, new Color(96,99,98));
g2.setPaint(gr);
g2.fill(new Ellipse2D.Double(2, 0, w-1, h-1));
g2.setPaint(new Color(203,207,203));
g2.fill(new Ellipse2D.Double(6, 4, 7, 7));
g.translate(-thumbBounds.x, -thumbBounds.y);
}
}
Try this:
JScrollPane table = new JScrollPane(content){
#SuppressWarnings("static-access")
#Override
public JScrollBar createVerticalScrollBar() {
return (new Scroler()).makeUI();
}
};
Worked for me

How to edit a curve in java

I am making a Java program which is able to draw a curve on JPanel on mouse events.
Now I want to ask after drawing that curve, how can I edit that curve?
This is my Java program:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.QuadCurve2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import javax.swing.*;
public class MouseTestHovercraft extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final int MAX_CLR = 5;
private static final Color CURRENT_LIST_COLOR = new Color(190, 190, 255);
private List<Color> colors = new ArrayList<Color>();
private boolean tracking = false;
private List<Point> currentList = null;
private BufferedImage bufferedImage = new BufferedImage(PREF_W, PREF_H,
BufferedImage.TYPE_INT_ARGB);
private Random random = new Random();
This contructor is used to change the color of the curve as soon as mouse is released.
public MouseTestHovercraft() {
for (int redIndex = 0; redIndex < MAX_CLR; redIndex++) {
int r = (redIndex * 256) / (MAX_CLR - 1);
r = (r == 256) ? 255 : r;
for (int greenIndex = 0; greenIndex < MAX_CLR; greenIndex++) {
int g = (greenIndex * 256) / (MAX_CLR - 1);
g = (g == 256) ? 255 : g;
for (int blueIndex = 0; blueIndex < MAX_CLR; blueIndex++) {
int b = (blueIndex * 256) / (MAX_CLR - 1);
b = (b == 256) ? 255 : b;
Color c = new Color(r, g, b);
colors.add(c);
}
}
}
add(new JToggleButton(new AbstractAction("TrackMouse") {
public void actionPerformed(ActionEvent ae) {
trackMouse(ae);
}
}));
add(new JButton(new AbstractAction("Clear Image") {
public void actionPerformed(ActionEvent e) {
bufferedImage = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
repaint();
}
}));
MyMouseAdapter myMA = new MyMouseAdapter();
addMouseListener(myMA);
addMouseMotionListener(myMA);
}
This is used to listen the event of tracking button.
private void trackMouse(ActionEvent ae) {
JToggleButton toggleBtn = (JToggleButton) ae.getSource();
tracking = toggleBtn.isSelected();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public void msg(String message) {
System.out.println(message);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bufferedImage, 0, 0, null);
if (currentList != null) {
drawList(g, currentList, CURRENT_LIST_COLOR, 1f);
}
}
This will draw a curve on jpanel using quadcurve
private void drawList(Graphics g, List<Point> ptList, Color color,
float strokeWidth) {
if (ptList.size() > 1) {
Graphics2D g2 = (Graphics2D) g.create();
// Graphics2D g2 = (Graphics2D) g;
g2.setColor(color);
// g2.setStroke(new BasicStroke(strokeWidth));
QuadCurve2D selectedCurve = null;
for (int j = 0; j < ptList.size() - 1; j++) {
int x1 = ptList.get(j).x;
int y1 = ptList.get(j).y;
int x2 = ptList.get(j + 1).x;
int y2 = ptList.get(j + 1).y;
selectedCurve =new QuadCurve2D.Float(x1, y1, 5, 5, x2,y2);
g2.draw(selectedCurve);
}
g2.dispose();
}
}
On mouse press this code will first add the starting point into currentlist list and after that till mouse released all the points are added into currentlist.
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
if (tracking && e.getButton() == MouseEvent.BUTTON1) {
currentList = new ArrayList<Point>();
currentList.add(e.getPoint());
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (tracking && e.getButton() == MouseEvent.BUTTON1) {
currentList.add(e.getPoint());
Graphics2D g2 = bufferedImage.createGraphics();
Color color = colors.get(random.nextInt(colors.size()));
drawList(g2, currentList, color, 3f);
currentList = null;
repaint();
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (tracking && currentList != null) {
currentList.add(e.getPoint());
repaint();
}
}
}
private static void createAndShowGui() {
MouseTestHovercraft mainPanel = new MouseTestHovercraft();
JFrame frame = new JFrame("MouseMotion Eg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setResizable(false);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

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;
}
}
}

Categories