JTextArea - get the line of the current mouse position - java

i want to get the line of the current mousePosition in an JTextArea.
I cant find a method to get the line using the coordinates which i receive from the MouseMotionAdapter -> event.getPoint();.
Has anyone an idea, how i could do it?

Here is simple example with help of viewToModel() and getLineOfOffset() methods:
import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
public class TestFrame extends JFrame {
private JTextArea area;
private JLabel l;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
area = new JTextArea(5,5);
area.addMouseMotionListener(getListener());
l = new JLabel(" ");
add(new JScrollPane(area));
add(l,BorderLayout.SOUTH);
}
private MouseMotionListener getListener() {
return new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent e) {
int viewToModel = area.viewToModel(e.getPoint());
if(viewToModel != -1){
try {
l.setText("line: "+(1+area.getLineOfOffset(viewToModel)));
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
#Override
public void mouseDragged(MouseEvent e) {
}
};
}
public static void main(String args[]) {
new TestFrame();
}
}

Related

JFrame.repaint() and JFrame.revalidate() not working

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class TheSize extends JFrame implements ActionListener, KeyListener {
static String inText="";
JPanel pane=new JPanel();
JLabel word0=new JLabel("I would like my grid to be 2^",JLabel.RIGHT);
JLabel word1=new JLabel("* 2^ "+inText,JLabel.RIGHT);
JButton finish=new JButton("I'm done");
JTextField size=new JTextField("",3);
public TheSize(){
super("size");
System.out.println("hi");
setLookAndFeel();
setSize(550,100);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FlowLayout box=new FlowLayout();
setLayout(box);
pane.add(word0);
pane.add(size);
pane.add(word1);
pane.add(finish);
finish.addActionListener(this);
add(pane);
setVisible(true);
pack();
size. addKeyListener(this);
setFocusable(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
public void actionPerformed(ActionEvent e) {
}
#Override
public void keyPressed(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent e) {
inText=size.getText();
pane.revalidate();
pane.repaint();
}
public static void main(String[] args){
new TheSize();
}
}
a couple of things
I made sure the KeyListener is working, and it is not working as in no output, it didn't give me any error.
What should happen:
It should pop a frame which says I would like my grid to be 2^__(user input Textfield)____* 2^(what is in the textfield). (Button for I'm done).
however, (what is in the textfield) remains empty after I type something into the text field. I checked whether the program heard my keystrokes using System.out.println();, and it is working, so the revalidate(); and repaint() commands must not be(I also tested it out by putting a System.out.println(); in my constructor. Thanks in advance
Never use a KeyListener on a JTextField. Get rid of the KeyListener and the JTextField should likely accept text just fine. Instead, if you want to register user input, use a DocumentListener if you just want the text but won't filter it, or a DocumentFilter if you need to filter the text before it is displayed. This sort of question has been asked many times on this site.
Also note that your JLabel will never change, even if you do use a DocumentListener since you call setText(...) on your word1 JLabel but never re-call this method. Just changing the String that the inText String variable refers to of course will not magically change the JLabel's displayed text.
Note, that I'm not sure what you mean by the replicate() command as I've not heard of this method. Do you mean revalidate() if so, please clarify.
For example:
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
// Avoid extending JFrames if at all possible.
// and only extend other components if needed.
#SuppressWarnings("serial")
public class TheSize2 extends JPanel {
private static final String FORMAT = "* 2^ %s";
private static final int PREF_W = 550;
private static final int PREF_H = 100;
private String inText = "";
private JLabel word0 = new JLabel("I would like my grid to be 2^", JLabel.RIGHT);
private JLabel word1 = new JLabel(String.format(FORMAT, inText), JLabel.RIGHT);
private JButton finish = new JButton("I'm done");
private JTextField size = new JTextField("", 3);
public TheSize2() {
finish.setAction(new FinishAction("I'm Done"));
size.getDocument().addDocumentListener(new SizeListener());
add(word0);
add(size);
add(word1);
add(finish);
}
#Override // make JPanel bigger
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = Math.max(superSz.width, PREF_W);
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class SizeListener implements DocumentListener {
private void textUpdated(DocumentEvent e) {
try {
inText = e.getDocument().getText(0, e.getDocument().getLength());
word1.setText(String.format(FORMAT, inText));
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
#Override
public void changedUpdate(DocumentEvent e) {
textUpdated(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
textUpdated(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
textUpdated(e);
}
}
private class FinishAction extends AbstractAction {
public FinishAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component comp = (Component) e.getSource();
if (comp == null) {
return;
}
Window win = SwingUtilities.getWindowAncestor(comp);
if (win == null) {
return;
}
win.dispose();
}
}
private static void createAndShowGui() {
TheSize2 theSize2 = new TheSize2();
JFrame frame = new JFrame("The Size");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(theSize2);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I found the solution with the help of Hovercraft Full Of Eels, all I missed was to re setSize. It is not the best solution, but it is simple enough for me to understand.
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class TheSize extends JFrame implements ActionListener, KeyListener {
static String inText="";
JPanel pane=new JPanel();
JLabel word0=new JLabel("I would like my grid to be 2^",JLabel.RIGHT);
JLabel word1=new JLabel("* 2^ "+inText,JLabel.RIGHT);
JButton finish=new JButton("I'm done");
JTextField size=new JTextField("",3);
public TheSize(){
super("size");
setLookAndFeel();
setSize(550,100);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FlowLayout box=new FlowLayout();
setLayout(box);
pane.add(word0);
pane.add(size);
pane.add(word1);
pane.add(finish);
finish.addActionListener(this);
add(pane);
setVisible(true);
pack();
size.addKeyListener(this);
setFocusable(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args){
new TheSize();
}
#Override
public void keyPressed(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
inText=size.getText();
word1.setText("* 2^ "+inText);
pane.revalidate();
pane.repaint();
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}

How to change background in JFrame consisting of JPanels?

I'm trying to change the background of my JFrame.
I tried using the setBackground(Color) method to all the JPanel objects and only the area covered between Buttons and all other fields is covered. Can anyone help me here?
output img:
code :
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JOptionPane;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JLabel;
import java.awt.event.WindowEvent;
import javax.swing.ImageIcon;
import javax.swing.UIManager;
public class calculator extends JFrame implements ActionListener, KeyListener
{
public JButton[] dig=new JButton[10];
public JButton sin,cos,tan,toNegative,add,subtract,divide,multiply,quad,clear,equals,result,back;
public JTextField txt,a,b,c;
public JPanel inputField,digits,quadSwitcher,eqCls,extras,zero,addSubt;
public int width=280,height=400;
public static String input="";
private ImageIcon img;
private Color color1=Color.ORANGE;
public calculator()
{
super("Calculator");try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}catch(Exception e){}
img=new ImageIcon("calc.png");
this.setIconImage(img.getImage());
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
setSize(width,height);
txt=new JTextField(null,20);
txt.setEditable(true);
inputField=new JPanel();
txt.setPreferredSize(new Dimension(width-50,30));
inputField.add(txt);
this.add(inputField);
txt.addKeyListener(this);
for(int i=0;i<10;i++)
dig[i]=new JButton(i+"");
sin=new JButton("sin");
cos=new JButton("cos");
tan=new JButton("tan");
toNegative=new JButton("+/-");
add=new JButton("add");
subtract=new JButton("Subtract");
add=new JButton("Add");
multiply=new JButton("Multiply");
quad=new JButton("Quadratic Equation");
quad.addActionListener(this);
divide=new JButton("Divide");
equals=new JButton("=");
quadSwitcher=new JPanel();
quadSwitcher.add(quad);
this.add(quadSwitcher);
digits=new JPanel();
digits.setLayout(new GridLayout(3,3,5,5));
for(int i=9;i>=1;i--)
digits.add(dig[i]);
extras=new JPanel();
extras.setLayout(new GridLayout(2,3,4,4));
extras.add(sin);
extras.add(cos);
extras.add(tan);
extras.add(toNegative);
extras.add(multiply);
extras.add(divide);
this.add(digits);
zero=new JPanel();
dig[0].setPreferredSize(new Dimension((width/2)-10,25));
zero.add(dig[0]);
this.add(zero);
this.add(extras);
addSubt=new JPanel();
addSubt.setLayout(new GridLayout(1,2,10,0));
addSubt.setPreferredSize(new Dimension(width-35,30));
addSubt.add(add);
addSubt.add(subtract);
this.add(addSubt);
eqCls=new JPanel();
eqCls.setLayout(new GridLayout(1,2,10,0));
eqCls.setPreferredSize(new Dimension(width-35,30));
clear=new JButton("clear");
eqCls.add(equals);
eqCls.add(clear);
clear.addActionListener(this);
this.add(eqCls);
for(int i=0;i<10;i++)
dig[i].addActionListener(this);
sin.addActionListener(this);
cos.addActionListener(this);
tan.addActionListener(this);
toNegative.addActionListener(this);
equals.addActionListener(this);
add.addActionListener(this);
subtract.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
setVisible(true);
this.setBackground(Color.ORANGE);
inputField.setBackground(color1);
quadSwitcher.setBackground(color1);
eqCls.setBackground(color1);
addSubt.setBackground(color1);
digits.setBackground(color1);
extras.setBackground(color1);
zero.setBackground(color1);
inputField.setOpaque(true);
JOptionPane.showMessageDialog(this,"Developed By Saksham Puri.");
}
public static void main(String args[])
{
calculator ob=new calculator();
}
#Override
public void keyPressed(KeyEvent e)
{
int keyCode=e.getKeyCode();
if(keyCode==KeyEvent.VK_ENTER){
input=txt.getText();
txt.setText(performOperation(input));}
}
#Override
public void actionPerformed(ActionEvent e)
{
String str=e.getActionCommand();
if(Character.isDigit(str.charAt(0))) txt.setText(txt.getText()+""+str);
else if(str.equalsIgnoreCase("clear"))
txt.setText("");
else if(str.equalsIgnoreCase("tan")) txt.setText(txt.getText()+""+str);
else if(str.equalsIgnoreCase("sin"))txt.setText(txt.getText()+""+str);
else if(str.equalsIgnoreCase("cos"))txt.setText(txt.getText()+""+str);
else if(str.equalsIgnoreCase("add"))txt.setText(txt.getText()+""+"+");
else if(str.equalsIgnoreCase("subtract"))txt.setText(txt.getText()+""+"-");
else if(str.equalsIgnoreCase("+/-"))txt.setText(txt.getText()+""+"-");
else if(str.equalsIgnoreCase("multiply"))txt.setText(txt.getText()+""+"*");
else if(str.equalsIgnoreCase("divide"))txt.setText(txt.getText()+""+"/");
else if(str.equalsIgnoreCase("=")){input=txt.getText(); txt.setText(performOperation(input));}
else if(str.equalsIgnoreCase("Quadratic Equation")) setQuad();
else if(str.equalsIgnoreCase("back"))back();
else if(str.equalsIgnoreCase("calculate")){back(); txt.setText(calcQuad()); revalidate(); repaint();}
}
public void back()
{
inputField.removeAll();
quadSwitcher.removeAll();
inputField.add(txt);
quadSwitcher.add(quad);
revalidate();
repaint();
}
public String calcQuad()
{
return Quad.solveQuad(Integer.parseInt(a.getText()),Integer.parseInt(b.getText()),Integer.parseInt(c.getText()));
}
public void setQuad()
{
inputField.removeAll();
quadSwitcher.removeAll();
a=new JTextField("a",4);
a.setEditable(true);
b=new JTextField("b",4);
b.setEditable(true);
c=new JTextField("c",4);
c.setEditable(true);
inputField.add(a);
inputField.add(new JLabel("x^2 + "));
inputField.add(b);
inputField.add(new JLabel("x + "));
inputField.add(c);
result=new JButton("Calculate");
back=new JButton("Back");
back.addActionListener(this);
result.addActionListener(this);
quadSwitcher.add(result);
quadSwitcher.add(back);
revalidate();
repaint();
}
#Override
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
public String performOperation(String str)
{
return "Performed Operation";
}
}
just the color
getContentPane().setBackground(Color.LIGHT_GRAY); //for example
put an image on the background
//create a JComponent to store your image
class ImagePanel extends JComponent
{
private Image image;
public ImagePanel(String str) {
BufferedImage image=null;
try {
image = ImageIO.read(new File(str));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
//in your JFrame class
ImagePanel contentPane = new ImagePanel("./background.png");
this.setContentPane(contentPane);
getContentPane().setBackground(Color.LIGHT_GRAY);// just in case your image does not fit the entire view

NimbusLookAndFeel and Jtable ... I Cant save?

This is My Main class
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import javax.swing.JButton;
public class Button extends JFrame {
public JPanel contentPane;
public SaveObject saveObject=new SaveObject();
public table frame1 ;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Button frame = new Button();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Button() {
NimbusLookAndFeel laf = new NimbusLookAndFeel();
try {
UIManager.setLookAndFeel(laf);
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
frame1=new table();;
JButton btnNewButton = new JButton("SAVE");
btnNewButton.setBounds(151, 99, 120, 52);
contentPane.add(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
saveObject.save(frame1);
}
});
}
}
This is My second Class
import java.io.Serializable;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class table implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
public String[] title={"1","2","3","4","5"};
public DefaultTableModel tableModel=new DefaultTableModel(title,0);
JFrame a=new JFrame();
JTable table = new JTable(tableModel) ;
public JScrollPane scrollPane=new JScrollPane();
public Object[] object=new Object[title.length];
public int practiceNumber=0;
public String[] premlesave=new String[100];
public table()
{
scrollPane.setBounds(0, 0, 396, 188);
table.setFillsViewportHeight(true);
a.setVisible(true);
a.add(scrollPane);
} }
And this is My saveobject Class
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.imageio.stream.FileImageInputStream;
public class SaveObject
{
private ObjectOutputStream output;
private ObjectInputStream input;
public void save(Object o)
{
try{
output = new ObjectOutputStream(new FileOutputStream("mm.ser"));
output.writeObject(o);;
output.close();
output.flush();
}
catch(IOException e)
{}
}
}
And now I want use NimbusLookAndFeel laf = new NimbusLookAndFeel(); but this is not Serializable and show error. Why? This means I cant use the NimbusLookAndFeel?

Keylistener not working with fullscreen

I have created a program in which a window opens which says click to start.When we press start button it opens another window and make it fullscreen. I have add keylistener to this fullscreen window to move an image.But its not working. If you wanna see the code please ask me .
public g1(){
panel = new JPanel();
cake = new ImageIcon("G:\\naman1.jpg").getImage();
start = new JButton("Start");
restart = new JButton("Restart");
exit = new JButton("EXIT");
panel.add(start);
panel.setFocusable(true);
start.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new g1().run(); //this method is from superclass it calls init }
}
);
panel.setBackground(Color.GRAY);
}
public void init(){
super.init(); //it makes the window fullscreen
Window w = s.getFullScreenWindow();
w.setFocusable(true);
w.addKeyListener(this);}
Try this:
The MainFrame
package moveimages;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainFrame extends JFrame {
JButton startBtn;
public MainFrame() {
this.setTitle("Moving Images");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(initComponents());
this.setSize(new Dimension(1024, 768));
this.setVisible(true);
}
private JPanel initComponents() {
JPanel jPanel = new JPanel();
startBtn = new JButton("start");
startBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final ImageWindow imageWindow = new ImageWindow();
}
});
jPanel.add(startBtn);
return jPanel;
}
}
This is the ImageWindow
package moveimages;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class ImageWindow extends JFrame {
public ImageWindow() {
this.add(new JLabel("Window"));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(screenSize.width, screenSize.height);
final ImagePanel imagePanel = new ImagePanel();
this.getContentPane().add(imagePanel);
this.setVisible(true);
}
class ImagePanel extends JPanel {
URL url;
int panelX;
int panelY;
boolean isDragged;
ImagePanel() {
this.panelX = this.getWidth();
this.panelY = this.getHeight();
try {
this.url = new URL("http://i.stack.imgur.com/XZ4V5.jpg");
final ImageIcon icon = new ImageIcon(url);
final JLabel imageLabel = new JLabel(icon);
Action moveLeft = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(imageLabel.getX() - 1 > 0)
imageLabel.setLocation(imageLabel.getX()-1, imageLabel.getY());
}
};
Action moveUp = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(imageLabel.getY() - 1 > 0) {
imageLabel.setLocation(imageLabel.getX(), imageLabel.getY()-1);
}
}
};
Action moveDown = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(getParent().getHeight()-icon.getIconHeight() > imageLabel.getY() + 1) {
imageLabel.setLocation(imageLabel.getX(), imageLabel.getY()+1);
}
}
};
Action moveRight = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(getParent().getWidth()-icon.getIconWidth() > imageLabel.getX()+1) {
imageLabel.setLocation(imageLabel.getX()+1, imageLabel.getY());
}
}
};
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("A"), "moveLeft");
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("W"), "moveUp");
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("S"), "moveDown");
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("D"), "moveRight");
imageLabel.getActionMap().put("moveLeft", moveLeft);
imageLabel.getActionMap().put("moveUp", moveUp);
imageLabel.getActionMap().put("moveDown", moveDown);
imageLabel.getActionMap().put("moveRight", moveRight);
this.add(imageLabel);
} catch (MalformedURLException ex) {
Logger.getLogger(ImageWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Start the App
package moveimages;
import javax.swing.SwingUtilities;
public class MoveImages {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MainFrame frame = new MainFrame();
});
}
}
Maybe it helps you to refactor your current app.

Adding background image to JPanel on button action

What is the best way to add a background image to a JPanel/JLabel when a JButton is called? I know how to get the JButton action and such. I just can't figure out or find a way to get the background image to change when that button is pressed.
Here is an example:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class ModifiableBackgroundFrame extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
private ImageIcon image;
private JPanel pan;
private JButton btn;
private int count = 0;
private static final String[] images =
{"http://www.dvd-ppt-slideshow.com/images/ppt-background/background-3.jpg",
"http://www.psdgraphics.com/wp-content/uploads/2009/02/abstract-background.jpg",
"http://hdwallpaperpics.com/wallpaper/picture/image/background.jpg",
"http://www.highresolutionpics.info/wp-content/uploads/images/beautiful-on-green-backgrounds-for-powerpoint.jpg"};
public ModifiableBackgroundFrame()
{
super("The title");
image = new ImageIcon();
btn = new JButton("Change background");
btn.setFocusPainted(false);
btn.addActionListener(this);
pan = new JPanel()
{
private static final long serialVersionUID = 1L;
#Override
public void paintComponent(Graphics g)
{
g.drawImage(image.getImage(), 0, 0, null);
}
};
pan.setPreferredSize(new Dimension(400, 400));
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(pan, BorderLayout.CENTER);
contentPane.add(btn, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new ModifiableBackgroundFrame();
}
});
}
#Override
public void actionPerformed(ActionEvent e)
{
btn.setEnabled(false);
btn.setText("Loading...");
new SwingWorker<Image, Void>()
{
#Override
protected Image doInBackground() throws Exception
{
return ImageIO.read(new URL(images[count++ % 4]));
}
#Override
protected void done()
{
try
{
image.setImage(get());
pan.repaint();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
catch(ExecutionException e)
{
e.printStackTrace();
}
btn.setText("Change background");
btn.setEnabled(true);
}
}.execute();
}
}
In your JButton's actionPerformed, you can call JLabel.setIcon(Icon) to set a background image.
final JLabel label = new JLabel();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(SOME_IMAGE));
}
}

Categories

Resources