How draw oval image in JLabel - java

I want to draw a oval image in a JLabel, using Graphics. This is my code, but a dont know about Graphics.
class imagePanel extends JLabel {
//private PlanarImage image;
private BufferedImage buffImage = null;
private void drawFingerImage(int nWidth, int nHeight, byte[] buff) {
buffImage = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_BYTE_GRAY);
buffImage.getRaster().setDataElements(0, 0, nWidth, nHeight, buff);
Graphics g = buffImage.createGraphics();
g.drawImage(buffImage, 0, 0, 140, 150, null);
g.dispose();
repaint();
}
public void paintComponent(Graphics g) {
g.drawImage(buffImage, 0, 0, this);
}
}
I have this

you need the help of setClip() method as mentioned here and here.
when it comes to code it should look like this
public class OvalImageLabel extends JLabel {
private Image image;
public OvalImageLabel(URL imageUrl) throws IOException {
image = ImageIO.read(imageUrl);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setClip(new java.awt.geom.Ellipse2D.Float(0f,0f, getWidth(),getHeight()/2));
g.drawImage(image, 0, 0, this);
}
}
and a running application that using this class
public class UsageExample extends JPanel {
public UsageExample() {
super(new BorderLayout());
OvalImageLabel l;
try {
l = new OvalImageLabel(new File("/path/to/image.png").toURI().toURL());
} catch (Exception e) {
e.printStackTrace();
return;
}
add(l, BorderLayout.CENTER);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setContentPane(new UsageExample());
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Related

Giving action listeners string qualities and using those strings in an if statement

As a sort of side project to teach myself action listeners, buttons, and Jframes I started a bit of a profiler based on TV shows and the like. The buttons and actionlisteners work but I just can't figure out how to give the action listeners strings and call on those strings. Where am I going wrong? Thank you in advance.
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ProfileCreatorWithoutRecords extends JFrame {
public static void main(String[] args) throws IOException {
final String dramaAnswer;
final String comedyStyleAnswer;
final String comedyShowAnswer;
final JFrame fridayFrame = new JFrame();
fridayFrame.setContentPane(new JPanel() {
BufferedImage image = ImageIO.read(new URL("http://s21.postimg.org/xfdlwcr2f/friday_night_lights_season_4_pictures.jpg"));
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 500, 350, this);
}
});
final JButton fridayButton = new JButton("Friday Night Lights");
fridayFrame.add(fridayButton);
fridayFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
fridayFrame.setSize(500, 350);
fridayFrame.setVisible(true);
fridayFrame.setLocation(0, 0);
///////////////////////////////////////////////////////////////////MAD MEN
final JFrame madFrame = new JFrame();
madFrame.setContentPane(new JPanel() {
BufferedImage image = ImageIO.read(new URL("http://s27.postimg.org/c1lxi135v/mad_men_1024x768.jpg"));
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 1024, 768, this);
}
});
final JButton madButton = new JButton("Mad Men");
madFrame.add(madButton);
madFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
madFrame.setSize(1024, 768);
madFrame.setVisible(true);
madFrame.setLocation(900,0);
////////////////////////////////////////HOUSE OF CARDS
final JFrame houseFrame = new JFrame();
houseFrame.setContentPane(new JPanel() {
BufferedImage image = ImageIO.read(new URL("http://cdn.bgr.com/2013/04/netflix-house-of-cards.jpg"));
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 620, 458, this);
}
});
final JButton houseButton = new JButton("House of Cards");
houseFrame.setVisible(true);
houseFrame.setSize(620, 458);
houseFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
houseFrame.add(houseButton);
houseFrame.setLocation(0, 400);
//////////////////////////////////////////////////////////////////////////////////GAFFIGAN
final JFrame gaffiganFrame = new JFrame();
gaffiganFrame.setContentPane(new JPanel() {
BufferedImage image = ImageIO.read(new URL("http://thepost.s3.amazonaws.com/wp-content/uploads/2015/02/Jim-Gaffigan-Wilbur-Artist1.jpg"));
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 550, 253, this);
}
});
final JButton gaffiganButton = new JButton("Clean comedy");
gaffiganFrame.setVisible(false);
gaffiganFrame.setSize(550, 253);
gaffiganFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
gaffiganFrame.add(gaffiganButton);
gaffiganFrame.setLocation(0, 0);
///////////////////////////////////////////////////////////////////////////////////LOUIE
final JFrame louieFrame = new JFrame();
louieFrame.setContentPane(new JPanel() {
BufferedImage image = ImageIO.read(new URL("http://static.dudeiwantthat.com/omg/video-clips/Louis-CK-Live-at-the-Beacon-Theater-1604.jpg"));
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 504, 420, this);
}
});
final JButton louieButton = new JButton("Dirty, rant comedy");
louieFrame.setVisible(false);
louieFrame.setSize(504, 420);
louieFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
louieFrame.add(louieButton);
louieFrame.setLocation(500, 0);
final JFrame officeFrame = new JFrame();
officeFrame.setContentPane(new JPanel() {
BufferedImage image = ImageIO.read(new URL("https://sarahsayswatchit.files.wordpress.com/2011/05/the-office.jpg"));
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 600, 600, this);
}
});
final JButton officeButton = new JButton("The Office");
officeFrame.setVisible(false);
officeFrame.setSize(600, 600);
officeFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
officeFrame.add(officeButton);
officeFrame.setLocation(0, 0);
final JFrame southFrame = new JFrame();
southFrame.setContentPane(new JPanel() {
BufferedImage image = ImageIO.read(new URL("http://2.images.southparkstudios.com/default/image.jpg?quality=0.8"));
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 480, 360, this);
}
});
final JButton southButton = new JButton("South Park");
southFrame.setVisible(false);
southFrame.setSize(480, 360);
southFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
southFrame.add(southButton);
southFrame.setLocation(650, 0);
final JFrame bigbangFrame = new JFrame();
bigbangFrame.setContentPane(new JPanel() {
BufferedImage image = ImageIO.read(new URL("http://1.bp.blogspot.com/-w8v5FzJwAdk/U_NlRh73i5I/AAAAAAAABsU/02yuF3IPs78/s1600/the-big-bang-theory%3DSatanismo.png"));
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 1000, 562, this);
}
});
final JButton bigbangButton = new JButton("Big Boob Blonde Lady");
bigbangFrame.setVisible(false);
bigbangFrame.setSize(1000, 562);
bigbangFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
bigbangFrame.add(bigbangButton);
bigbangFrame.setLocation(0, 800);
fridayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent fridayclicked) {
String dramaAnswer = "fridaynightlights";
fridayFrame.setVisible(false);
madFrame.setVisible(false);
houseFrame.setVisible(false);
gaffiganFrame.setVisible(true);
louieFrame.setVisible(true);
}
});
madButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent madclicked) {
dramaAnswer = "madmen";
madFrame.setVisible(false);
fridayFrame.setVisible(false);
houseFrame.setVisible(false);
gaffiganFrame.setVisible(true);
louieFrame.setVisible(true);
}
});
houseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent houseclicked) {
dramaAnswer = "houseofcards";
fridayFrame.setVisible(false);
houseFrame.setVisible(false);
madFrame.setVisible(false);
louieFrame.setVisible(true);
gaffiganFrame.setVisible(true);
}
});
gaffiganButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent cleanpicked) {
comedyStyleAnswer = "CleanComedy";
louieFrame.setVisible(false);
gaffiganFrame.setVisible(false);
officeFrame.setVisible(true);
southFrame.setVisible(true);
bigbangFrame.setVisible(true);
}
});
louieButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent dirtypicked) {
comedyStyleAnswer = "DirtyComedy";
louieFrame.setVisible(false);
gaffiganFrame.setVisible(false);
officeFrame.setVisible(true);
southFrame.setVisible(true);
bigbangFrame.setVisible(true);
}
});
officeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent officepicked) {
comedyShowAnswer = "Office";
officeFrame.setVisible(false);
southFrame.setVisible(false);
bigbangFrame.setVisible(false);
}
});
southButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent southpark) {
comedyShowAnswer = "southpark";
officeFrame.setVisible(false);
southFrame.setVisible(false);
bigbangFrame.setVisible(false);
}
});
bigbangButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent bigbang) {
comedyShowAnswer = "bigbang";
officeFrame.setVisible(false);
southFrame.setVisible(false);
bigbangFrame.setVisible(false);
}
});
}
giveReccomendation(dramaAnswer, comedyStyleAnswer, comedyShowAnswer);
}
public static void giveReccomendation (String dramaAnswer, String comedyStyleAnswer, String comedyShowAnswer) throws IOException {
System.out.println("public static void started");
JFrame personFrame = new JFrame();
personFrame.setContentPane(new JPanel() {
BufferedImage image = ImageIO.read(new URL("http://images.vcpost.com/data/images/full/29158/person-of-interest-on-cbs.jpg"));
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 1000, 650, this);
}
});
JLabel personLabel = new JLabel("Person Of Interest");
personFrame.add(personLabel);
personFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
personFrame.setSize(1000, 650);
personFrame.setVisible(false);
personFrame.setLocation(0, 0);
System.out.println("person frame created");
if (dramaAnswer.equalsIgnoreCase("fridaynightlights")
&& comedyStyleAnswer.equalsIgnoreCase("clean")
&& comedyShowAnswer.equalsIgnoreCase("office")) {
personFrame.setVisible(true);
System.out.println("person frame set visible");
}
}
}
Because you are placing your only call to giveRecommendation in your main thread, what you are doing is calling the method giveRecommendation after your frame and all of your listeners are set up.
While your action listeners will correctly in setting the value of your local Strings, they will perform no other actions.
Therefore if you want to call the giveRecommendation method, place it in one of your existing action listeners, or create a new button and action listener.
Creating multiples frames and then only showing one is not a very good design.
Maybe you can use:
a Card Layout, or.
a JTabbedPane.
I just can't figure out how to give the action listeners strings and call on those strings.
Not sure if I understand the question, but a JButton has a setActionCommand(...) method. This String can be accessed in the ActionEvent using the getActionCommand() method of the ActionEvent.
Read the section from the Swing tutorial on How to Use Buttons for more information and working examples.

How to fit IMG size into JPanel

I'm kinda doing a GUI where when you press the "NEXT" button, it shows one by one the images at some directory.
My question is: How can I fit the size of the IMGs with the JPanles dimensions, I'm working with 6 or more MP images and I need to see the entire image.
Here is the code that gives me the imageIcon and where I add it to the JPanel.
JButton btnNextImg = new JButton("Next IMG");
btnNextImg.setBounds(96, 179, 110, 23);
btnNextImg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (i == nImg)
i = 0;
try {
selectedImage = ImageIO.read(new File("C:\\IMAGES\\"+ String.valueOf(i+1) + ".jpg"));
iSelect = new ImageIcon(selectedImage);
originalImage.setIcon(iSelect);
} catch (IOException e1) {
e1.printStackTrace();
}
i++;
}
});
contentPane.add(btnNextImg);
And where I add it.
JPanel panel = new JPanel();
originalImage = new JLabel();
panel.add(originalImage);
panel.setBounds(5, 226, 309, 280);
contentPane.add(panel);
Thank you so much.
here's an image panel i found somewhere on the internet when i had the same problem:
public class ImagePanel extends JPanel {
private java.awt.Image image;
private boolean stretched = true;
private int xCoordinate;
private int yCoordinate;
public ImagePanel() {
}
public ImagePanel(Image image) {
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
if (isStretched()) {
g.drawImage(image, xCoordinate, yCoordinate, getWidth(), getHeight(), this);
} else {
g.drawImage(image, xCoordinate, yCoordinate, this);
}
}
}
public java.awt.Image getImage() {
return image;
}
public void setImage(java.awt.Image image) {
this.image = image;
repaint();
}
public boolean isStretched() {
return stretched;
}
public void setStretched(boolean stretched) {
this.stretched = stretched;
repaint();
}
public int getXCoordinate() {
return xCoordinate;
}
public void setXCoodinate(int xCoordinate) {
this.xCoordinate = xCoordinate;
}
public int getYCoordinate() {
return xCoordinate;
}
public void setYCoordinate(int yCoordinate) {
this.yCoordinate = yCoordinate;
repaint();
}
}
to add an image to the panel use something like this:
ImagePanel imagePanel = new ImagePanel();
BufferedImage image = ImageIO.read(new File("C:\\IMAGES\\"+ String.valueOf(i+1) + ".jpg"));
imagePanel.setImage(image);
Here is the code that gives me the imageIcon and where I add it to the JPanel.
Check out Darryl's Stretch Icon. It will allow the Icon to fill the entire space available to the JLabel.

Scaling an image quickly, and making sure it actually scales

I am trying to scale a screenshot taken by:
robot.createScreenCapture(SCREEN_RECT);
Im trying to get it down to an image that is 600X400 and fits into a JFrame that is 600X400
My program is using a swing worker to create an video out of each picture, or frames. The frames have a delay of 200ms per each. the image when told to rescale just shows the original image at the original dimensions. Does anyone know how to fix this, or should I just give up on the resize-ing?
#SuppressWarnings("serial")
public class temporaryShit extends JPanel
{
private static final int width = 600;
private static final int height = 400;
private JLabel displayedLabel = new JLabel();
public temporaryShit()
{
setLayout(new BorderLayout());
add(displayedLabel);
try {
MySwingWorker mySwingWorker = new MySwingWorker();
mySwingWorker.execute();
} catch (AWTException e) {
}
}
public void setLabelIcon(Icon icon) {
displayedLabel.setIcon(icon);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
private class MySwingWorker extends SwingWorker<Void, Icon>
{
private final Rectangle SCREEN_RECT = new Rectangle(0, 0, width, height);
private long delay = 200;
private Robot robot = null;
public MySwingWorker() throws AWTException
{
robot = new Robot();
}
#Override
protected Void doInBackground() throws Exception
{
Timer utilTimer = new Timer();
TimerTask task = new TimerTask()
{
#Override
public void run()
{
BufferedImage capturedImage = captureScreen();
publish(new ImageIcon(capturedImage));
}
};
utilTimer.scheduleAtFixedRate(task, delay, delay);
return null;
}
#Override
protected void process(List<Icon> chunks)
{
for (Icon icon : chunks)
{
setLabelIcon(icon);
}
}
private BufferedImage captureScreen()
{
BufferedImage img = robot.createScreenCapture(SCREEN_RECT);
return createResizedImage(img, width, height);
}
public BufferedImage createResizedImage(Image original, int width, int height)
{
BufferedImage scaledBI = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = scaledBI.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(original, 0, 0, width, height, null);
g.dispose();
return scaledBI;
}
}
private static void createAndShowGui()
{
temporaryShit mainPanel = new temporaryShit();
JFrame frame = new JFrame("SwingWorker Eg");
frame.setDefaultCloseOperation(JFrame.EXIT_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();
}
});
}
}
You already have a new image with specified size - scaled, which you can use for rendering.
Here is a simple example:
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
class TestBrightness {
public static void main(String args[]) {
try {
URL imageUrl = new URL(
"http://duke.kenai.com/comfyChair/ComfyChairRadSmall.jpg");
BufferedImage ioImage = ImageIO.read(imageUrl);
JPanel panel = new JPanel();
Image scaledImg = ioImage.getScaledInstance(ioImage.getWidth() / 2,
ioImage.getHeight() / 2, Image.SCALE_SMOOTH);
panel.add(new JLabel(new ImageIcon(ioImage)));
panel.add(new JLabel(new ImageIcon(scaledImg)));
JOptionPane.showMessageDialog(null, panel, "100% vs 50%",
JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Failure",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
}
As a side note, there are many ways to scale an image and Image.getScaledInstance() may not be the best. You may be interested to take a look at The Perils of Image.getScaledInstance() for some details on Image.getScaledInstance()
EDIT: question update
Last question update removed all the details regarding getScaledInstance and invalidated this answer. getScaledInstance is a very slow method and it is also asynchronous. Try this method to get a resized image:
public static BufferedImage createResizedImage(Image original, int width,
int height) {
BufferedImage scaledBI = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = scaledBI.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(original, 0, 0, width, height, null);
g.dispose();
return scaledBI;
}
You may want to change rendering hints for better quality.
For a nicer and more complete image scaler take a look at getFasterScaledInstance() from Filthy Rich Clients book.
EDIT : last question update with posted code and SwingWorker
The implementation of SwingWorker is not correct. doInBackground() schedules java.Utils.Timer. This timer handles all updates, while the actual SwingWorker worker thread ends. All updates from the timer are fired not on Event Dispatch Thread. It may not be safe to allocate ImageIcon not on EDT. And for sure it is not safe to update UI, ie calling setLabelIcon() not on EDT. See Concurrency in Swing tutorial for details.
You can add while loop and Thread.sleep in doInBackground() and remove the timer. Alternatively, Swing timer may be more suitable for this case. Here is an example:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class DemoRobotPanel extends JPanel{
private static final long serialVersionUID = 1L;
private Image image;
private Robot robot;
private Rectangle CAPTURE_RECT;
private int TIMER_DELAY = 1000;
private int desiredWidth = 600;
private int desiredHeight = 400;
public DemoRobotPanel() {
CAPTURE_RECT = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
try {
robot = new Robot();
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
BufferedImage img = robot.createScreenCapture(CAPTURE_RECT);
setImage(img);
} catch (HeadlessException e) {
e.printStackTrace();
}
}
};
Timer timer = new Timer(TIMER_DELAY, taskPerformer);
timer.start();
} catch (AWTException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(desiredWidth, desiredHeight);
}
public void setImage(Image image) {
this.image = image;
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null)
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
private static void createAndShowGui() {
final DemoRobotPanel panel = new DemoRobotPanel();
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Try this:
public BufferedImage resize(BufferedImage bufferedImage, int resizeWidth, int resizeHeight) {
// Create new (blank) image of required (scaled) size
BufferedImage scaledImage = new BufferedImage(resizeWidth, resizeHeight, BufferedImage.TYPE_INT_ARGB);
// Paint scaled version of image to new image
Graphics2D graphics2D = scaledImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(bufferedImage, 0, 0, resizeWidth, resizeHeight, null);
graphics2D.dispose();
return scaledImage;
}
You may want to try different RenderingHints.

Write text into a JTextPane with an image background

I have a JTextPane with an image for its background.
prevWords = new JTextPane()
{
public void paint(Graphics g)
{
BufferedImage img;
try
{
img = ImageIO.read(new File("Images/logo.png"));
img.getGraphics().setColor(new Color(Color.TRANSLUCENT));
g.drawImage(img, 0, 0, null);
}
catch (IOException e)
{
System.out.println("Failed to load logo.");
}
super.paintComponents(g);
}
};
When I write text to the the pane, it I cannot see it. I have set the text in pane to be white as well.
This is a complete hack.
The problem here is, the UI is painting the background twice...
You need to circumvent the UI in such a way so that you can paint the image into the background while still getting the text to render over the top.
In the end, I had to make the text pane transparent so I could force the UI not to paint the background.
public class TextPaneBackground {
public static void main(String[] args) {
new TextPaneBackground();
}
public TextPaneBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(new TextPaneWithBackground()));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TextPaneWithBackground extends JTextPane {
private BufferedImage background;
public TextPaneWithBackground() {
try {
background = ImageIO.read(new File("C:/Users/shane/Dropbox/MegaTokyo/Evil_Small.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
setForeground(Color.WHITE);
setOpaque(false);
}
#Override
public Dimension getPreferredScrollableViewportSize() {
return background == null ? super.getPreferredScrollableViewportSize() : new Dimension(background.getWidth(), background.getHeight());
}
#Override
public Dimension getPreferredSize() {
return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
if (isOpaque()) {
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
}
if (background != null) {
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight()- background.getHeight()) / 2;
g2d.drawImage(background, x, y, this);
}
getUI().paint(g2d, this);
g2d.dispose();
}
}
}
Reimeus hinted at the ability to insert an image into the Document directly, this might be a better, long term solution.

Jslider is laggy after overriding paint method

After overriding the paintTrack and paintThumb method of my JSlider it lags if I drag its thumb.
I've replaced the track and thumb with images. Any ideas how to solve the problem?
public class test {
private static JFrame frame;
private static JSlider slider;
public static void main(String[] args) throws IOException {
frame = new JFrame();
slider = new JSlider();
slider.setUI(new MySliderUI(slider));
frame.add(slider);
frame.setVisible(true);
frame.pack();
frame.setSize(1200, 720);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static class MySliderUI extends BasicSliderUI {
private BufferedImage imgTrack;
private BufferedImage imgThumb;
public MySliderUI(JSlider slider) throws IOException {
super(slider);
imgTrack = ImageIO.read(new File("icon/track.png"));
imgThumb = ImageIO.read(new File("icon/thumb.png"));
}
#Override
public void paintTrack(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Rectangle t = trackRect;
g2d.drawImage(imgTrack, t.x, t.y, t.width, t.height, null);
}
#Override
public void paintThumb(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
Rectangle t = thumbRect;
g2d.drawImage(imgThumb, t.x, t.y, null);
}
}
}
EDIT:
Solved it, I also had to override the getThumbSize()
#Override
protected Dimension getThumbSize() {
return new Dimension(imgThumb.getWidth(), imgThumb.getHeight());
}

Categories