I build a game in which I want to add a buffered image on existing background image icon, My code is for this game is:
public class Hunter extends JFrame {
JPanel panel = new JPanel();
JLabel label = new JLabel(new ImageIcon("F:\\workspace\\HunterGame\\src\\huntergame\\background.jpg"));
BufferedImage image;
Graphics g;
Hunter(){
setSize(961, 694);
setResizable(false);
setTitle("Hunter");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
panel.add(label);
add(panel);
addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent me) {
}
#Override
public void mousePressed(MouseEvent me) {
int x = me.getX();
int y = me.getY();
if((x>11&&x<69)&&(y>26&&y<69)){
dispose();
new menu();
}
}
#Override
public void mouseReleased(MouseEvent me) {
}
#Override
public void mouseEntered(MouseEvent me) {
}
#Override
public void mouseExited(MouseEvent me) {
}
});
try {
image = ImageIO.read(new File("F:\\workspace\\HunterGame\\src\\huntergame\\hunter.png"));
} catch (IOException ex) {
System.out.println("Exception Occurs");
}
JLabel label1 = new JLabel(new ImageIcon(image));
label.add(label1);
revalidate();
}
}
I also tried Graphics.drawImage() method but this didn't work.
My background image is on JLabel and label is on frame and for second image label1 is on label but I also tried this on JPanel and no result showing.
Output Screen show only background image.
Please help me out in this.
Regards.
If you want to add a second label to the background label then you need to set the layout manager of the label.
The basic code would be something like:
JLabel background = new JLabel(....);
background.setLayout( new FlowLayout() );
JLabel foreground = new JLabel(...);
background.add( foreground );
frame.add(background, BorderLayout.CENTER);
frame.pack();
frame.setVisible( true );
Related
Here are the requirements in detail:
one fixed sized image on the top in a JPanel
depending on the different input, a hint JLabel shows or hides below the image
the panel should have the same size as the image when there is no hint label showing
Here is the sample code:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container panel = frame.getContentPane();
BorderLayout boxLayout = new BorderLayout();
panel.setLayout(boxLayout);
JLabel fixedLabel = new JLabel("fixed");
fixedLabel.setBackground(Color.green);
fixedLabel.setOpaque(true);
fixedLabel.setMinimumSize(new Dimension(600, 120));
fixedLabel.setPreferredSize(new Dimension(600, 120));
fixedLabel.setMaximumSize(new Dimension(600, 120));
panel.add(fixedLabel, BorderLayout.NORTH);
JLabel lbl = new JLabel("can be hidden");
fixedLabel.addMouseListener(new MouseListener() {
boolean showButton = false;
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
if (!showButton) {
showButton = true;
panel.add(lbl, BorderLayout.CENTER);
panel.revalidate();
panel.repaint();
} else {
showButton = false;
panel.remove(lbl);
panel.revalidate();
panel.repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
frame.pack();
frame.setVisible(true);
when the first time clicked, the panel won't automatically enlarge vertically. after manually enlarged, click again and the panel won't automatically shrink to the top label size
Please guide me on how to proceed.
I figured it out with below code
panel.addContainerListener(new ContainerListener() {
#Override
public void componentAdded(ContainerEvent e) {
System.out.println("added");
System.out.println(panel.getBounds());
Rectangle bounds = frame.getBounds();
bounds.height +=38;
frame.setBounds(bounds);
frame.revalidate();
frame.repaint();
System.out.println(frame.getBounds());
}
#Override
public void componentRemoved(ContainerEvent e) {
System.out.println("removed");
System.out.println(panel.getBounds());
Rectangle bounds = frame.getBounds();
bounds.height -= 38;
frame.setBounds(bounds);
frame.revalidate();
frame.repaint();
System.out.println(frame.getBounds());
}
});
I don't really know how to word this question, but I can explain what I'm trying to do.
I have my program drawing a basic menu with a background image and 3 buttons along the bottom. I want to make it so that when I press one of the buttons, the menu and the background image change to a different scene. Like pressing play to start a game or pressing options to go to an option menu.
This is my code for the primary menu:
private final void initUI() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
add(panel);
panel.add(Box.createVerticalGlue());
JPanel bottom = new JPanel();
bottom.setAlignmentX(1f);
bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
JButton plyBtn = new JButton("Play");
plyBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
GameFrame_Test1 game1 = new GameFrame_Test1();
game1.setVisible(true);
}
});
JButton opBtn = new JButton("Options");
JButton quitButton = new JButton("Exit");
quitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
bottom.add(plyBtn);
bottom.add(Box.createRigidArea(new Dimension(100, 0)));
bottom.add(opBtn);
bottom.add(Box.createRigidArea(new Dimension(100, 0)));
bottom.add(quitButton);
bottom.add(Box.createRigidArea(new Dimension(100, 0)));
panel.add(new GraphicTest_1());
panel.add(bottom);
panel.add(Box.createRigidArea(new Dimension(0,15)));
setTitle("Justice GUI");
setSize(1280, 720);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
DisplayFrame ex = new DisplayFrame();
ex.setVisible(true);
}
});
}
This is my code for the frame I want to change to so far:
class GameFrame_Test1 extends JPanel{
private Image mshi;
public GameFrame_Test1() {
loadImage();
setSurfaceSize();
}
private void loadImage() {
mshi = new ImageIcon("content/Placeholder_Map.png").getImage();
}
private void setSurfaceSize() {
Dimension d = new Dimension();
d.width = mshi.getWidth(null);
d.height = mshi.getHeight(null);
setPreferredSize(d);
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(mshi, 0, 0, null);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
I am very new to Java Swing, and this is a test program for me to learn how to use it. I have looked online for a solution, but not being able to word my question makes it hard. Thanks to anyone who can help!
I want to make it so that when I press one of the buttons, the menu and the background image change to a different scene.
You should be using a Card Layout as the layout manager of the content panel. Then you can swap a different panel on the frame when a button is clicked.
Check out the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
I want to create a window where there is a background image and components on top of that. I have managed to get the components and background 'stacked', but my problem is positioning the components.
I have tried using AbsoluteLayout but it doesn't seem to work.
This is my (beginner) code thus far:
public class RegionPrompt extends JPanel {
public RegionPrompt () throws IOException {
JFrame frame = new JFrame("Map");
GridBagConstraints gbc = new GridBagConstraints();
JPanel pane = new JPanel() {
URL image2 = getClass().getResource("map.jpg");
BufferedImage image = ImageIO.read(image2);
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), this);
}
};
frame.setContentPane(pane);
JPanel pane2 = new JPanel();
pane2.setOpaque(false);
pane2.setSize(DefaultGUI.defaultSize);
pane2.setLayout(new GridBagLayout());
JButton c = new JButton("Map Location");
//gbc.gridx = 0;
//gbc.gridy = 0;
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Location information", JOptionPane.INFORMATION_MESSAGE);
}
});
pane2.add(c,gbc);
frame.add(pane2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(653, 448);
frame.setVisible(true);
}
}
Any help (as well as forgiveness for this code chunk) is greatly appreciated!
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();
}
});
}
}