I'm working on this project in Java and need an image to display, along with a bio, and button that plays a song/sound. I finished the button and bio but I can figure out how to get the image to display in the NORTH part of the layout along with the button in the center part, any help would be great.
This is my error: The method add(String, Component) in the type Container is not applicable for the arguments (Image, String)
public void init() {
// image
myPicture = getImage(getCodeBase(), "sample.jpg");
// THIS IS WHERE MY PROBLEM IS vvvvvvv
add(myPicture, BorderLayout.NORTH);
add(bio);
paneSouth.add(play);
getContentPane().add(paneSouth, BorderLayout.SOUTH);
mySound = getAudioClip(getDocumentBase(), "sample.wav");
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mySound.play();
}});
}
public void paint(Graphics g){
g.drawImage(myPicture, 10, 10, this);
}
private JPanel paneSouth = new JPanel();
private TextArea bio = new TextArea("bio thing");
private JButton play = new JButton("Play");
private AudioClip mySound;
private Image myPicture;
}
EDIT:
public void init() {
// image
ImageIcon icon = new ImageIcon(myPicture);
JLabel myLabelImage = new Image(icon);
add(myLabelImage, BorderLayout.NORTH);
// bio
add(bio);
add(bio, BorderLayout.CENTER);
// sound
paneSouth.add(play);
getContentPane().add(paneSouth, BorderLayout.SOUTH);
mySound = getAudioClip(getDocumentBase(), "sample.wav");
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mySound.play();
}});
}
private JPanel paneSouth = new JPanel();
private TextArea bio = new TextArea("bio.");
private JButton play = new JButton("Play");
private AudioClip mySound;
private Image myPicture;
}
I guess you are using JApplet because you are using Swing components. Try something like this:
public class ImageApplet extends JApplet {
private JPanel paneSouth = new JPanel();
private JTextArea bio = new JTextArea("bio thing");
private JButton play = new JButton("Play");
private Image myPicture;
private ImageIcon icon;
private JLabel label;
public void init() {
try {
URL pic = new URL(getDocumentBase(), "sample.jpg");
myPicture = ImageIO.read(pic);
icon = new ImageIcon(myPicture);
label = new JLabel(icon);
} catch (Exception e) {
e.printStackTrace();
}
// add image
add(label, BorderLayout.NORTH);
// bio
add(bio, BorderLayout.CENTER);
// sound
paneSouth.add(play);
add(paneSouth, BorderLayout.SOUTH);
// here add your sound declaration and button event...
}
#Override
public void paint(Graphics g) {
super.paint(g);
}
}
And try change your TextArea for a JTextArea since you are only using swing components.
Related
I would like to simply add a JLabel into a JButton and center it horizontally. I've tried many thing but the text stay left side... Here is my code :
JLabel labeltest = new JLabel("Simple test");
JButton myButton = new JButton();
myButton.setHorizontalTextPosition(SwingConstants.CENTER);
myButton.add(labeltest);
Create an Icon of the text and give the Icon the foreground/background colors that you want.
I tried this but the problem comes when I had to do button.setenabled(false); after this the text becomes almost invisible
You can set the disabled Icon to be the same as the Icon and it will not be painted in the disabled state:
JButton button = new JButton( new ImageIcon(...) );
button.setDisabledIcon( button.getIcon() );
button.setEnabled(false);
Of course the problem with this approach is that the user doesn't know the button is disabled. So in reality you would need 2 icons:
one for the normal state
one for the disabled state
A JButton is also a java.awt.Container. Thus you can set a layout manager. E.g. you can use a GridBagLayout.
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
JToggleButton toggleButton = new JToggleButton();
JLabel jLabel = new JLabel("3");
JToggleButton.ToggleButtonModel toggleButtonModel = (JToggleButton.ToggleButtonModel) toggleButton.getModel()
ToggleForegroundAction toggleForegroundAction =
new ToggleForegroundAction(toggleButtonModel, Color.WHITE, Color.RED);
toggleForegroundAction.setComponent(jLabel);
toggleButton.setAction(toggleForegroundAction);
toggleButton.setLayout(new GridBagLayout());
toggleButton.add(jLabel, new GridBagConstraints());
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
panel.setLayout(new BorderLayout());
panel.add(toggleButton, BorderLayout.CENTER);
Container contentPane = frame.getContentPane();
contentPane.add(panel);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
An action that toggles the label's foreground color might look like this
public class ToggleForegroundAction extends AbstractAction {
private JComponent component;
private JToggleButton.ToggleButtonModel toggleButtonModel;
private final Color selectedColor;
private final Color unselectedColor;
public ToggleForegroundAction(JToggleButton.ToggleButtonModel toggleButtonModel, Color selectedColor, Color unselectedColor) {
this.toggleButtonModel = toggleButtonModel;
this.selectedColor = selectedColor;
this.unselectedColor = unselectedColor;
}
public void setComponent(JComponent component) {
this.component = component;
setForeground(component, toggleButtonModel.isSelected());
}
#Override
public void actionPerformed(ActionEvent e) {
JComponent targetComponent = this.component;
if (targetComponent == null) {
targetComponent = (JComponent) e.getSource();
}
setForeground(targetComponent, toggleButtonModel.isSelected());
}
private void setForeground(JComponent targetComponent, boolean isSelected) {
Color foreground;
if (isSelected) {
foreground = selectedColor;
} else {
foreground = unselectedColor;
}
targetComponent.setForeground(foreground);
}
}
=>
I'm using JLayeredPanel to put two panels on top of each other. The first panel would act like a background and the second panel which uses JFileChooser to get the user's image to print on the panel then that panel will lay on top of the first panel with a button click.
I've sucessfully get the image to print onto the second panel fron JFileChooser but unable to get the second panel to lay on top of the first panel.
Here's the outline.
http://s8.postimg.org/ofblrk179/outline.png
Here's my code.
...
public class DesignerUI extends JFrame {
public DesignerUI() {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
DesignerUI frame = new DesignerUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
card2 = new JPanel();
cards.add(card2, "Design");
card2.setLayout(null);
JButton btnGraphic = new JButton("Add Graphic");
btnGraphic.setBounds(0, 0, 400, 53);
panel.add(btnGraphic);
btnGraphic.addActionListener(new chooseGraphic());
JLayeredPane lp = new JLayeredPane();
lp.setPreferredSize(new Dimension(300,400));
lp.setBounds(400,0,382,406);
card2.add(lp);
panel_1 = new JPanel();
panel_1.setBounds(0, 0, 383, 406);
picPanel = new JPanel();
picPanel.setBounds(105, 115, 213, 200);
lp.add(picPanel, new Integer(2));
lp.add(panel_1, new Integer(3));
private class chooseGraphic implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame graphicInputWindow = new JFrame();
new graphicInputWindow();
}
}
public class graphicInputWindow extends JFrame {
JButton button;
JButton select;
JLabel label;
JPanel picPanel;
Image image;
public graphicInputWindow() {
super("Select Your Image");
setResizable(false);
button = new JButton("Browse");
button.setBounds(300, 300, 100, 40);
select = new JButton("Select");
select.setBounds(400, 300, 100, 40);
picPanel = new JPanel();
label = new JLabel();
label.setBounds(10, 10, 670, 250);
add(button);
add(select);
add(picPanel);
add(label);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System
.getProperty("user.home")));
// filter the files
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"*.Images", "jpg", "gif", "png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
// if the user click on save
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
label.setIcon(ResizeImage(path));
}
// if the user click on cancel
else if (result == JFileChooser.CANCEL_OPTION) {
System.out.println("No File Select");
}
}
});
select.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// if user click select
JPanel picPanel = new JPanel(new BorderLayout());
picPanel.add(label);
lp.add(picPanel);
lp.setVisible(true);
//close window returns to card2
setVisible(false);
}
});
setSize(700, 400);
setVisible(true);
revalidate();
contentPane.revalidate();
contentPane.repaint();
}
public ImageIcon ResizeImage(String ImagePath) {
ImageIcon MyImage = new ImageIcon(ImagePath);
Image img = MyImage.getImage();
Image newImg = img.getScaledInstance(panel_1.getWidth(),
panel_1.getHeight(), Image.SCALE_SMOOTH);
ImageIcon image = new ImageIcon(newImg);
return image;
}
/*protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}*/
}
}
I've made two buttons in frame .I want to know how to display different images on clicking different buttons?
is there another way out or i have to make panel?I am at beginner stage
package prac;
import java.awt.*;
import java.awt.event.*;
public class b extends Frame implements ActionListener{
String msg;
Button one,two;
b()
{ setSize(1000,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
one=new Button("1");
two=new Button("2");
add(one);
add(two);
one.addActionListener(this);
two.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
msg=e.getActionCommand();
if(msg.equals("1"))
{
msg="Pressed 1";
}
else
msg="pressed 2";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,100,300);
}
public static void main(String s[])
{
new b();
}
}
Use JLabel and change the icon when button is clicked.
Some points:
call setVisible(true) in the end after adding all the component.
use JFrame#pack() method that automatically fit the components in the JFrame based on component's preferred dimension instead of calling JFrame#setSize() method.
sample code:
final JLabel jlabel = new JLabel();
add(jlabel);
final Image image1 = ImageIO.read(new File("resources/1.png"));
final Image image2 = ImageIO.read(new File("resources/2.png"));
JPanel panel = new JPanel();
JButton jbutton1 = new JButton("Show first image");
jbutton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
jlabel.setIcon(new ImageIcon(image1));
}
});
JButton jbutton2 = new JButton("Show second image");
jbutton2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
jlabel.setIcon(new ImageIcon(image2));
}
});
panel.add(jbutton1);
panel.add(jbutton2);
add(panel, BorderLayout.NORTH);
I want to create a "preview window" for my "main window", so if I take mouse pointer to a particular button or place then it show main window preview in a small window, and when I click on that "preview window" then it should return to the "main window". For example Windows 7 task bar creates a preview for each opened application. How can I can offer this feature to my users?
E.G.
An extremely simplistic implementation.
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
class ShowPreviews {
class ToolTipListener extends MouseAdapter {
JWindow toolTip;
JLabel label;
Component preview;
ToolTipListener(Component preview) {
this.preview = preview;
}
#Override
public void mouseEntered(MouseEvent me) {
if (toolTip==null) {
toolTip = new JWindow();
label = new JLabel();
toolTip.add(label);
}
label.setIcon( new ImageIcon(
getScaledImageOfComponent(preview, .6) ) );
toolTip.pack();
Component c = (Component)me.getSource();
int x = c.getLocationOnScreen().x+(c.getWidth()/2);
int y = c.getLocationOnScreen().y+c.getHeight();
toolTip.setLocation(x,y);
toolTip.setVisible(true);
}
#Override
public void mouseExited(MouseEvent me) {
toolTip.setVisible(false);
toolTip.dispose();
}
public Image getScaledImageOfComponent(
Component component, double scale) {
BufferedImage bi = new BufferedImage(
(int)(component.getWidth()*scale),
(int)(component.getHeight()*scale),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.scale(scale, scale);
component.paint(g);
g.dispose();
return bi;
}
}
ShowPreviews() {
JPanel gui = new JPanel(new BorderLayout(2,2));
final CardLayout cards = new CardLayout();
final JPanel cardPanel = new JPanel(cards);
JPanel treePanel = new JPanel();
JTree tree = new JTree();
tree.setVisibleRowCount(5);
tree.expandRow(2);
treePanel.add(new JScrollPane(tree));
cardPanel.add(treePanel, "tree");
JPanel labelPanel = new JPanel(new GridLayout(0,1,2,2));
for (int ii=1; ii<7; ii++) {
labelPanel.add(new JLabel("Label " + ii));
}
cardPanel.add(new JScrollPane(labelPanel), "label");
JToolBar uiSelectors = new JToolBar();
// we should use a ButtonGroup for the cards,
// but plain buttons look better on hover.
JButton treeButton = new JButton("Tree");
treeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
cards.show(cardPanel, "tree");
}
});
uiSelectors.add(treeButton);
treeButton.addMouseListener( new ToolTipListener(treePanel));
JButton labelButton = new JButton("Label");
labelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
cards.show(cardPanel, "label");
}
});
uiSelectors.add(labelButton);
labelButton.addMouseListener( new ToolTipListener(labelPanel));
gui.add(uiSelectors, BorderLayout.NORTH);
gui.add(cardPanel, BorderLayout.CENTER);
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
// start the GUI on the EDT
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ShowPreviews();
}
});
}
}
I am trying to get a JLabel to appear when a JButton is clicked. I have added an action listener and added the component to the layout. I am using the label1.setVisible(true) when the JButton is clicked in actionPerformed. I still can't get it work. Can some look at my code?
public class LearnAppMain extends JFrame implements ActionListener {
// Define variables
public JButton button1;
public JLabel label1;
public JTextField field1;
private Image image1;
private String apple = "apple.jpg";
public LearnAppMain() {
ImageIcon image1 = new ImageIcon(this.getClass().getResource(apple));
JLabel label1 = new JLabel(image1);
button1 = new JButton("A");
button1.addActionListener(this);
field1 = new JTextField(10);
// Create layout
setLayout(new FlowLayout());
// create Container
final Container cn = getContentPane();
cn.add(button1);
cn.add(field1);
cn.add(label1);
// setLayout(new FlowLayout());
setSize(250, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (e.getSource() == button1) {
label1.setVisible(true);
field1.setText("Apple");
}
}
}
I have my main method in another class file. The error I get leads me to the label1.setVisible(true);
Every question I've seen they say to do this, but I'm wondering if there is something else that needs to be added.
There were a couple of issues here:
Your label1 was hidden by doing JLabel label in the constructor. You basically declared another variable called label1 in your constructor that hid the one in the class itself.
Your label was visible on the startup - I used label.setVisible(false) for the test, but you might want otherwise
I also put the creation of Image aside as I did not have an image, so uncomment that and change as appropriate.
Here's a complete working version:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LearnAppMain extends JFrame implements ActionListener {
// Define variables
public JButton button1;
public JLabel label1;
public JTextField field1;
private Image image1;
private String apple = "apple.jpg";
public LearnAppMain() {
//ImageIcon image1 = new ImageIcon(this.getClass().getResource(apple));
//JLabel label1 = new JLabel(image1);
label1 = new JLabel("hello");
label1.setVisible(false);
button1 = new JButton("A");
button1.addActionListener(this);
field1 = new JTextField(10);
// Create layout
setLayout(new FlowLayout());
// create Container
final Container cn = getContentPane();
cn.add(button1);
cn.add(field1);
cn.add(label1);
// setLayout(new FlowLayout());
setSize(250, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (e.getSource() == button1) {
label1.setVisible(true);
field1.setText("Apple");
}
}
public static void main(String[] args) {
new LearnAppMain();
}
}
I'd suggest using separate (usually inner-class) ActionListener instances instead of overriding actionPerformed. See e.g. this for a similar example if you are interested:
http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/events/BeeperProject/src/events/Beeper.java
Also, if you are using this in a bigger application (i.e. not just experimenting or for prototyping), make sure all Swing code is run on EDT.
You typically use SwingUtilities.invokeLater for that purpose.
Hope this helps.
first you don't add the image first itself to JLabel.
just create the object and leave it like..
ImageIcon image1 = new ImageIcon(this.getClass().getResource(apple));
JLabel label1 = new JLabel("");
label1.setVisible(true);
then do the modification in the action performed
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1)
{
field1.seticon(image1);
field1.revalidate();
}
it will definitely works
clientDetail.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e){
d.getContentPane().removeAll();
g = new GridBagLayout();
gc = new GridBagConstraints();
d.setLayout(g);
JLabel message= new JLabel(" Message");
addComponent(message,5,1,1,2);
JTextArea Message = new JTextArea();
addComponent(Message,5,1,1,2);
d.setVisible(true);
d.setVisible(true);
d.pack();
}
private void addComponent(Component component, int i, int i0, int i1, int i2) {
gc.gridx=i;
gc.gridy=i0;
gc.gridheight=i1;
gc.gridwidth=i2;
g.setConstraints(component, gc);
add(component);
}
});
Recep.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});