Swing splash screen not working, Unexpected result - java

Downloaded some code to display Splash Screen from O'Reilly, but When I do some modified some text to display as per need.
I did some investigation, and debug the program but found nothing.
Is that any windows platform issue?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
public class SplashScreen extends JWindow {
private int duration;
byte[] msg = new byte[]{65,112,114,105,108,32,70, 111, 111,108};
String text = "";
public SplashScreen(int d) {
duration = d;
}
// A simple little method to show a title screen in the center
// of the screen for the amount of time given in the constructor
public void showSplash() throws Exception {
JPanel content = (JPanel)getContentPane();
content.setBackground(Color.white);
// Set the window's bounds, centering the window
int width = 450;
int height =300;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screen.width-width)/2;
int y = (screen.height-height)/2;
setBounds(x,y,width,height);
JLabel txt = new JLabel
(new String(msg), JLabel.CENTER);
txt.setFont(new Font("Sans-Serif", Font.BOLD, 32));
// Build the splash screen
JLabel label = new JLabel(new ImageIcon("oreilly.gif"));
JLabel copyrt = new JLabel
(new String(msg), JLabel.CENTER);
URL url = new URL("http://findicons.com/files/icons/360/emoticons/128/satisfied.png");
BufferedImage img = ImageIO.read(url);
ImageIcon icon = new ImageIcon(img);
JLabel iconL = new JLabel(icon);
copyrt.setFont(new Font("Sans-Serif", Font.BOLD, 12));
content.add(label, BorderLayout.CENTER);
content.add(txt, BorderLayout.CENTER);
content.add(iconL, BorderLayout.CENTER);
content.add(copyrt, BorderLayout.SOUTH);
Color oraRed = new Color(156, 20, 20, 255);
content.setBorder(BorderFactory.createLineBorder(oraRed, 10));
// Display it
setVisible(true);
// Wait a little while, maybe while loading resources
try { Thread.sleep(duration); } catch (Exception e) {}
setVisible(false);
}
public void showSplashAndExit() {
try {
showSplash();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
public static void main(String[] args) {
// Throw a nice little title page up on the screen first
SplashScreen splash = new SplashScreen(10000);
// Normally, we'd call splash.showSplash() and get on with the program.
// But, since this is only a test...
splash.showSplashAndExit();
}
}

Related

How to center buttons in my java game menu

So, basically, I've never really worked with windows in java, and I need help centering things. I tried a bunch of things, but no matter what, I can't center my buttons on my java menu.
Here's my main class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
public class window extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage canvas;
public window(int width, int height) {
canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
public Dimension getPreferredSize() {
return new Dimension(canvas.getWidth(), canvas.getHeight());
}
public void paint(Graphics g){
// double CanvasTileHeight = (canvas.getHeight()/16)+1;
// double CanvasTileWidth = (canvas.getWidth()/16)+1;
//
// OpenSimplexNoise noise = new OpenSimplexNoise();
//
// for(int j=0;j<CanvasTileWidth;j++) {
// double NoiseForCurrentLoopPos;
// if (((noise.eval(j,2)+1)*2)+16 < CanvasTileHeight) {
// NoiseForCurrentLoopPos = ((noise.eval(j,2)+1)*2)+16;
// } else {
// NoiseForCurrentLoopPos = CanvasTileHeight;
// }
// for(int i=(int) CanvasTileHeight;i>NoiseForCurrentLoopPos;i--) {
// Image sand = Toolkit.getDefaultToolkit().getImage("src/images/misc/sand.png");
// g.drawImage(sand, j*16, i*16, this);
// }
// }
//
// Image image = Toolkit.getDefaultToolkit().getImage("src/images/misc/Player_Placeholder1.png");
//
// ImageObserver paintingChild = null;
// g.drawImage(image, canvas.getWidth()/2-image.getWidth(paintingChild)/2, canvas.getHeight()/2-image.getHeight(paintingChild)/2, this);
//
}
public static void main(String[] args) throws ClassNotFoundException, IOException {
int width = 640;
int height = 480;
JFrame frame = new JFrame("Example Frame");
window panel = new window(width, height);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
JPanel buttons = new JPanel();
BoxLayout boxlayout = new BoxLayout(buttons, BoxLayout.Y_AXIS);
buttons.setLayout(boxlayout);
buttons.setBorder(new EmptyBorder(new Insets(150, 200, 150, 200)));
JLabel bottomLabel = new JLabel("GAME NAME HERE", SwingConstants.CENTER);
buttons.add(bottomLabel);
JButton jb1 = new JButton("Button 1");
JButton jb2 = new JButton("Button 2");
JButton jb3 = new JButton("Button 3");
jb1.setAlignmentX(SwingConstants.CENTER);
jb2.setAlignmentX(SwingConstants.CENTER);
jb3.setAlignmentX(SwingConstants.CENTER);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb1);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb2);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb3);
frame.add(buttons);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// loadtest();
// System.out.println(Arrays.toString(((String) test1).split(",")));
//
// savetest();
dirtest();
}
public static void savetest() {
String TestArray[] = {"hi87er629087029648276540982", "hi2", "hi3", "hi4", "Not gonna keep going on like this lol"};
String Test = TestArray[0];
String world = "testworld101022";
for (int k = 0; k < TestArray.length-1; k++) {
Test = Test + "," + TestArray[k+1];
}
new File("src\\saves\\" + world).mkdir();
try(FileOutputStream f = new FileOutputStream("src\\saves\\" + world + "\\chunk1savetest1.txt");
ObjectOutput s = new ObjectOutputStream(f)) {
s.writeObject(Test);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
static Object test1 = null;
public static void loadtest() {
String world = "testworld101022";
try(FileInputStream in = new FileInputStream("src\\saves\\" + world + "\\chunk1savetest1.txt");
ObjectInputStream s = new ObjectInputStream(in)) {
test1 = s.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void dirtest() {
File dir = new File("src\\saves");
File[] files = dir.listFiles();
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
System.out.println(files.length);
if (files.length == 0) {
System.out.println("No saves yet!");
} else {
for (int i = 0; i< files.length; i++) {
File filename = files[i];
System.out.println(filename.toString());
}
}
}
}
My problem is when I run it, this is what happens:
So, the buttons and/or test are not centered. I don't understand why.
My problem is, the buttons should be about where the red line on the image is, but no matter what I do, I can't get it to work.
I tried centering it with SwingConstants.CENTER, but that diden't work, so I also tried Component.CENTER_ALIGNMENT, but that did the exact same thing. I found that doing multiple different things like changing the code to
jb1.setAlignmentX(Component.CENTER_ALIGNMENT);
jb2.setAlignmentX(SwingConstants.CENTER);
jb3.setAlignmentX(SwingConstants.CENTER);
makes it like this:
so basically it makes it so the 2 that are different from the one I changed are correctly centered, but the one I changed it not. All the images and stuff are probably unnecessary, but I hope I got across what I need help with! thanks =)
You can use BoxLayout to do that, take a look at the following code:
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.util.Arrays;
public class Main
{
public static void main(final String[] args)
{
final JLabel label = new JLabel("GAME NAME HERE");
final JButton button1 = new JButton("Button 1");
final JButton button2 = new JButton("Button 2");
final JButton button3 = new JButton("Button 3");
final JPanel centerPanel = createCenterVerticalPanel(5, label, button1, button2, button3);
final JFrame frame = new JFrame();
frame.add(centerPanel);
frame.setVisible(true);
frame.pack();
}
private static JPanel createCenterVerticalPanel(final int spaceBetweenComponents, final JComponent... components)
{
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Arrays.stream(components).forEach(component -> {
component.setAlignmentX(JPanel.CENTER_ALIGNMENT);
panel.add(component);
panel.add(Box.createRigidArea(new Dimension(0, spaceBetweenComponents)));
});
return panel;
}
}
If you also want to center a panel vertically in a frame, just use frame.setLayout(new GridBagLayout()). Cheers!

JButton Release Action

I am trying to create an action on a JButton release and I am not sure how to accomplish this. I can make an action just fine when the button is pressed. When the button is pressed it will change the image to a red dot and when released it should change back to a default green dot.
My button press code is below if someone can point me in the direction on how to create an action when the button is released that would be most helpful. Thanks!
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == change1) {
p1a.setIcon(CLR); // THIS IS THE IMAGE WHEN BUTTON PRESSED
// WOULD LIKE TO CHANGE BACK TO DEFAULT IMAGE HERE WHEN BUTTON IS RELEASED
}
}
I'm not looking for an Icon on the button itself to change I am looking for the image to change in a JPanel....same concept though
Nice to have that information available ahead of time
One approach might be to attach a listener to the ButtonModel and monitor for it's state changes...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import javax.swing.ButtonModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Icon normalIcon;
private Icon pressedIcon;
public TestPane() {
setBorder(new EmptyBorder(16, 16, 16, 16));
normalIcon = makeIcon(Color.GREEN);
pressedIcon = makeIcon(Color.RED);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JLabel label = new JLabel(normalIcon);
JButton btn = new JButton("Pressy");
add(btn, gbc);
add(label, gbc);
btn.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = btn.getModel();
if (model.isArmed()) {
label.setIcon(pressedIcon);
} else {
label.setIcon(normalIcon);
}
}
});
}
protected Icon makeIcon(Color color) {
BufferedImage img = new BufferedImage(25, 25, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(color);
g2d.fillOval(0, 0, 25, 25);
g2d.dispose();
return new ImageIcon(img);
}
}
}
When the button is pressed it will change the image to a red dot and when released it should change back to a default green dot.
This can be entirely achieved within the JButton. See things like setPressedIcon(Icon) ..
E.G.
import javax.swing.*;
import java.net.*;
public class ButtonIcons {
ButtonIcons() throws MalformedURLException {
ImageIcon redIcon = new ImageIcon(new URL(
"https://i.stack.imgur.com/wCF8S.png"));
ImageIcon grnIcon = new ImageIcon(new URL(
"https://i.stack.imgur.com/T5uTa.png"));
JButton button = new JButton("Click me!", grnIcon);
button.setPressedIcon(redIcon);
JOptionPane.showMessageDialog(null, button);
}
public static void main(String[] args) {
Runnable r = () -> {
try {
ButtonIcons o = new ButtonIcons();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
};
SwingUtilities.invokeLater(r);
}
}

JTabbedPane Not working with Button and ComboBox as expected

I am having a problem with Java's Swing library. I added an Admission Class to JTabbedPane. The Button and ComboBox components on the first tab appear not to be working but, but when I remove setLayout(null) it seems to work, but this leads to other problems with the layout...
Below is what I have tried thus far:
DBProjectPractice.java
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
public class DBProjectPractice extends JFrame {
private Container contentPane;
private String User = null;
public String getUser() {
String user = this.User;
return user;
}
public DBProjectPractice() {
// TODO Auto-generated constructor stub
init();
}
JTabbedPane pane = new JTabbedPane();
JTabbedPane createTabbedPane() { // tab pane init
pane.addTab("text", new Admission()); // 입사 탭의 레이아웃.
pane.addTab("text", new JLabel("text.", JLabel.CENTER));
pane.addTab("text", new JLabel("text.", JLabel.CENTER));
pane.addTab("text", new JLabel("text.", JLabel.CENTER));
return pane;
}
public void init() {
contentPane = this.getContentPane();
contentPane.setLayout(new BorderLayout(30, 30));
setTitle("text");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTabbedPane jtabbedpane = createTabbedPane();
contentPane.add(new Top(), BorderLayout.NORTH);
contentPane.add(jtabbedpane, BorderLayout.CENTER);
setLocationByPlatform(true);
setSize(1600, 1000); // 사이즈 설정 // 가로 세로
setVisible(true); // 표시
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new DBProjectPractice();
}
}
Top.java
import java.awt.Font;
import java.awt.Graphics;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JPanel;
class Top extends JPanel{
#Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
Date date = new Date();
SimpleDateFormat text = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
Font f = new Font("Times", Font.BOLD, 15);
g.setFont(f);
g.drawString("text : " , 100, 25);
g.drawString("text : " + text.format(date), 1200, 25);
this.setSize(1600, 30);
}
}
Admission.java
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;
public class Admission extends JPanel {
private Container pane;
public Admission() {
// TODO Auto-generated constructor stub
setLayout(null);
Admission_Button();
FixLable_JLabel();
ComboBox();
}
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
Font f = new Font("Times", Font.BOLD, 15); // 글꼴 설정
g.setFont(f); // 글꼴 지정
g.drawString(":::: text ::::", 100, 100);
g.drawString(":::: text ::::", 100, 500);
this.setSize(1600, 30);
}
private void Admission_Button() { // 입사 탭의 레이아웃의 버튼
JButton[] Button = new JButton[3];
Button[0] = new JButton(" text ");
Button[1] = new JButton(" text ");
Button[2] = new JButton(" text ");
for(int i = 0; i < 3; i++) {
Button[i].setSize(100,40);
Button[i].setLocation(1065 + i * 120, 130);
add(Button[i]);
}
}
private void FixLable_JLabel() {
JLabel[] FixLabel = new JLabel[15]; // 고정된 label;
String[] FixLabelName = { "text", "text", "text","text","text","text","text","text","text","text",
"text","text","text","text","text"};
EtchedBorder eb = new EtchedBorder(Color.BLACK, Color.GRAY); // 테두리를 넣는다.
int FixLableIndex = 0;
for (String name : FixLabelName) {
FixLabel[FixLableIndex] = new JLabel(name);
FixLabel[FixLableIndex].setHorizontalAlignment(SwingConstants.CENTER); // 가운대 정렬
FixLabel[FixLableIndex].setBorder(eb); // 테두리 추가
FixLabel[FixLableIndex++].setSize(120, 30);
}
for(int i = 0 ; i < 7 ; i++) {
FixLabel[i].setLocation(100,200 + i * 30);
}
int t = 0;
for(int i = 7 ; i < 10 ; i++) {
FixLabel[i].setLocation(550,230 + t++ * 30);
}
FixLabel[10].setLocation(550, 350);
t = 0;
for(int i = 11 ; i < 14 ; i++) {
FixLabel[i].setLocation(1050,230 + t++ * 30);
}
FixLabel[14].setLocation(1050, 350);
for(int i = 0 ; i < 15; i++) {
add(FixLabel[i]);
}
}
private void ComboBox() {
String[] type = {"text", "text","text","text"};
JComboBox<String> typeCombo = new JComboBox<String>();
int num = type.length;
for(int i = 0 ; i < num ; i++) {
typeCombo.addItem(type[i]);
}
typeCombo.setBounds(220, 200, 1200, 30);
typeCombo.setSelectedItem(2);
add(typeCombo);
setVisible(true);
}
}
Your biggest problem (to me) seems to be that you're calling setSize(...) on your component within its own paintComponent method, a painting method:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Font f = new Font("Times", Font.BOLD, 15);
g.setFont(f);
g.drawString(":::: text ::::", 100, 100);
g.drawString(":::: text ::::", 100, 500);
this.setSize(1600, 30); // **** HERE ****
}
This is not correct and in fact dangerous, because it may try to change the component's size on any repaint, which then calls repaint almost recursively. Also the size that you're setting it to is unreasonable as a height of 30 can't possibly display the GUI that this JPanel holds. Don't do this.
Better:
to set size once via setSize(...) within the components constructor.
Better still to instead set preferred size by calling setPreferredSize(Dimension d) within the constructor.
Even better still is to instead override the component class's getPreferredSize().
Your other problem is that you're using null layouts. Again, while null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.

Backup for image that is drawn on in Java

In my application, there are things marked on an image by clicking on the image. That is done by setting the image as an Icon to a JLabel and adding a MousePressed method
I want to add a feature for the users to redo the last step now and need a backupimage for that.
The following is a code example:
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class BuffImgTest {
private BufferedImage buffimg, scaledimg, backupscaledimg;
private Image img;
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BuffImgTest window = new BuffImgTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public BuffImgTest() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
final JLabel label = new JLabel("");
label.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
Graphics graphics = scaledimg.getGraphics();
graphics.setColor(Color.RED);
graphics.drawString("Test", arg0.getX(), arg0.getY());
Image img = Toolkit.getDefaultToolkit().createImage(
scaledimg.getSource());
label.setIcon(new ImageIcon(img));
}
});
label.setBounds(10, 34, 414, 201);
try {
buffimg = ImageIO.read(new File("test.jpg"));
scaledimg = getScaledImage(buffimg, label.getWidth(),
label.getHeight());
backupscaledimg = scaledimg;
// backupscaledimg=getScaledImage(buffimg,label.getWidth(),label.getHeight());
Image img = Toolkit.getDefaultToolkit().createImage(
scaledimg.getSource());
label.setIcon(new ImageIcon(img));
} catch (Exception e) {
System.out.println(e);
}
frame.getContentPane().add(label);
JButton btnNewButton = new JButton("Restart Step");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
scaledimg = backupscaledimg;
Image img = Toolkit.getDefaultToolkit().createImage(
scaledimg.getSource());
label.setIcon(new ImageIcon(img));
}
});
btnNewButton.setBounds(111, 238, 89, 23);
frame.getContentPane().add(btnNewButton);
}
public static BufferedImage getScaledImage(BufferedImage image, int width,
int height) throws IOException {
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
double scaleX = (double) width / imageWidth;
double scaleY = (double) height / imageHeight;
AffineTransform scaleTransform = AffineTransform.getScaleInstance(
scaleX, scaleY);
AffineTransformOp bilinearScaleOp = new AffineTransformOp(
scaleTransform, AffineTransformOp.TYPE_BILINEAR);
return bilinearScaleOp.filter(image, new BufferedImage(width, height,
image.getType()));
}
}
It is not working as intended.
If I use the commented line backupscaledimg = getScaledImage(buffimg,label.getWidth(),label.getHeight()); instead of backupscaledimg = scaledimg;, it is working as expected.
The problem is that I want to do several steps of drawing things on the image, and it can only be redone the first time like that. From what I know the problem might be, that the command backupscaledimg = scaledimg is only creating a pointer for backupscaledimg pointing to scaledimg which results in both of them altering.
I don't want to save a new imagefile on each step though.
Is there any way around this? (found the scaling function on here by the way thanks for that anonymous)
Made some changes
Using GridBagLayout
Able to reset back to original image by pressing "Restart Step"
Able to undo last action with the use of an image stack (i.e. a Stack of BufferedImage)
Example code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Stack;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class BuffImgTest {
private BufferedImage scaledImg, originalScaledImg;
private JFrame frame;
private Stack<BufferedImage> imageStack = new Stack<>();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BuffImgTest window = new BuffImgTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public BuffImgTest() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
JPanel panel = new JPanel(new GridBagLayout());
final JLabel imgLabel = new JLabel("");
imgLabel.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
// Add current image to the image stack
imageStack.add(copyImage(scaledImg));
// Change the image
Graphics graphics = scaledImg.getGraphics();
graphics.setColor(Color.BLACK);
graphics.setFont(new Font("Arial", Font.BOLD, 32));
graphics.drawString("TEST", arg0.getX(), arg0.getY());
// Update label
Image img = Toolkit.getDefaultToolkit().createImage(
scaledImg.getSource());
imgLabel.setIcon(new ImageIcon(img));
}
});
imgLabel.setSize(500, 500);
imgLabel.setPreferredSize(new Dimension(500, 500));
try {
BufferedImage buffImg = ImageIO.read(new File("test.jpg"));
scaledImg = getScaledImage(buffImg, imgLabel.getWidth(),
imgLabel.getHeight());
// Clone it first
originalScaledImg = copyImage(scaledImg);
Image img = Toolkit.getDefaultToolkit().createImage(
scaledImg.getSource());
imgLabel.setIcon(new ImageIcon(img));
} catch (Exception e) {
System.out.println(e);
}
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(20, 10, 10, 10);
panel.add(imgLabel, c);
JButton restartBtn = new JButton("Restart Step");
restartBtn.setFont(new Font("Arial", Font.ITALIC, 20));
restartBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// Clear the image stack
imageStack.clear();
// Reset the image
scaledImg = copyImage(originalScaledImg);
Image img = Toolkit.getDefaultToolkit().createImage(
scaledImg.getSource());
imgLabel.setIcon(new ImageIcon(img));
}
});
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 10, 5, 10);
panel.add(restartBtn, c);
JButton undoBtn = new JButton("Undo Last");
undoBtn.setFont(new Font("Arial", Font.ITALIC, 20));
undoBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(imageStack.isEmpty()) {
JOptionPane.showMessageDialog(frame, "Cannot undo anymore!");
return;
}
// Get the previous image
scaledImg = copyImage(imageStack.pop());
Image img = Toolkit.getDefaultToolkit().createImage(
scaledImg.getSource());
imgLabel.setIcon(new ImageIcon(img));
}
});
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(5, 10, 20, 10);
panel.add(undoBtn, c);
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.setSize(800, 800);
}
/** For copying image */
public static BufferedImage copyImage(BufferedImage source){
BufferedImage b = new BufferedImage(
source.getWidth(), source.getHeight(), source.getType());
Graphics g = b.getGraphics();
g.drawImage(source, 0, 0, null);
g.dispose();
return b;
}
public static BufferedImage getScaledImage(BufferedImage image, int width,
int height) throws IOException {
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
double scaleX = (double) width / imageWidth;
double scaleY = (double) height / imageHeight;
AffineTransform scaleTransform = AffineTransform.getScaleInstance(
scaleX, scaleY);
AffineTransformOp bilinearScaleOp = new AffineTransformOp(
scaleTransform, AffineTransformOp.TYPE_BILINEAR);
return bilinearScaleOp.filter(image, new BufferedImage(width, height,
image.getType()));
}
}
Edited Image:
Image after pressing "Restart step":
Pressing "Undo Last" when image stack is empty:
Note:
Code for copying image is from this answer by APerson

Zoom in and zoom out function in Jpanel

I have to add Zoom In and Zoom Out functionality to JPanel, which contains components like JLabel with ImageIcon.
I want to Zoom JPanel with their components appropriately
I tried with following code snippet but it did not work properly.
The JPanel which is having null layout and is itself placed inside an Applet.
I am unsure of the reason as to why it is not working either because of Applet or something else !!
cPanel is my JPanel which contains JLabel
Following code snippet on Zoom Button click,
it shows blink screen on button click after that as original
Graphics g = cPanel.getGraphics();
Graphics2D g2d = (Graphics2D) g;
AffineTransform savedXForm = g2d.getTransform();
g2d.scale(1.0, 1.0);
g2d.setColor(Color.red);
super.paint(g);
g2d.setTransform(savedXForm);
cPanel.validate();
cPanel.repaint();
You can have a look into this link:
http://blog.sodhanalibrary.com/2015/04/zoom-in-and-zoom-out-image-using-mouse_9.html#.Vz6iG-QXV0w
Source Code to Refer(Here it has been accomplished using MouseWheelListener):
import java.awt.EventQueue;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import com.mortennobel.imagescaling.ResampleOp;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageZoom {
private JFrame frmImageZoomIn;
private static final String inputImage = "C:\\my-pfl-pic.jpg"; // give image path here
private JLabel label = null;
private double zoom = 1.0; // zoom factor
private BufferedImage image = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ImageZoom window = new ImageZoom();
window.frmImageZoomIn.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws IOException
*/
public ImageZoom() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws IOException
*/
private void initialize() throws IOException {
frmImageZoomIn = new JFrame();
frmImageZoomIn.setTitle("Image Zoom In and Zoom Out");
frmImageZoomIn.setBounds(100, 100, 450, 300);
frmImageZoomIn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
frmImageZoomIn.getContentPane().add(scrollPane, BorderLayout.CENTER);
image = ImageIO.read(new File(inputImage));
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// display image as icon
Icon imageIcon = new ImageIcon(inputImage);
label = new JLabel( imageIcon );
panel.add(label, BorderLayout.CENTER);
panel.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation();
double temp = zoom - (notches * 0.2);
// minimum zoom factor is 1.0
temp = Math.max(temp, 1.0);
if (temp != zoom) {
zoom = temp;
resizeImage();
}
}
});
scrollPane.setViewportView(panel);
}
public void resizeImage() {
System.out.println(zoom);
ResampleOp resampleOp = new ResampleOp((int)(image.getWidth()*zoom), (int)(image.getHeight()*zoom));
BufferedImage resizedIcon = resampleOp.filter(image, null);
Icon imageIcon = new ImageIcon(resizedIcon);
label.setIcon(imageIcon);
}
}

Categories