I am encountering problems with event handling in java.
I want to add the image1 if button 1 is pressed, image2 if button 2 is pressed, et cetera.
This is my code till now; Can anyone help? This code doesn't compile.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.ImageIcon;
public class MyPanel extends JPanel {
private JLabel jcomp1;
private JButton jcomp2;
private JButton jcomp3;
private JButton jcomp4;
private JButton jcomp5;
private JButton jcomp6;
private JButton jcomp7;
private JButton jcomp8;
private JButton jcomp9;
private ImageIcon image1;
private ImageIcon image2;
private ImageIcon image3;
private ImageIcon image4;
private ImageIcon image5;
private ImageIcon image6;
private ImageIcon image7;
private ImageIcon image8;
public MyPanel() {
//construct components
image1 = new ImageIcon(getClass().getResource("hang1.jpg"));
image2 = new ImageIcon(getClass().getResource("hang2.jpg"));
image3 = new ImageIcon(getClass().getResource("hang3.jpg"));
image4 = new ImageIcon(getClass().getResource("hang4.jpg"));
image5 = new ImageIcon(getClass().getResource("hang5.jpg"));
image6 = new ImageIcon(getClass().getResource("hang6.jpg"));
image7 = new ImageIcon(getClass().getResource("hang7.jpg"));
image8 = new ImageIcon(getClass().getResource("hang8.jpg"));
jcomp1 = new JLabel (image1);
jcomp2 = new JButton ("1");
jcomp3 = new JButton ("2");
jcomp4 = new JButton ("3");
jcomp5 = new JButton ("4");
jcomp6 = new JButton ("5");
jcomp7 = new JButton ("6");
jcomp8 = new JButton ("7");
jcomp9 = new JButton ("8");
//events
jcomp2.setActionCommand("1");
jcomp3.setActionCommand("2");
jcomp4.setActionCommand("3");
jcomp5.setActionCommand("4");
jcomp6.setActionCommand("5");
jcomp7.setActionCommand("6");
jcomp8.setActionCommand("7");
jcomp9.setActionCommand("8");
jcomp2.addActionListener(new ButtonClickListener());
jcomp3.addActionListener(new ButtonClickListener());
jcomp4.addActionListener(new ButtonClickListener());
jcomp5.addActionListener(new ButtonClickListener());
jcomp6.addActionListener(new ButtonClickListener());
jcomp7.addActionListener(new ButtonClickListener());
jcomp8.addActionListener(new ButtonClickListener());
jcomp9.addActionListener(new ButtonClickListener());
//adjust size and set layout
setPreferredSize(new Dimension(624, 537));
setLayout(null);
//add components
add(jcomp2);
add(jcomp3);
add(jcomp4);
add(jcomp5);
add(jcomp6);
add(jcomp7);
add(jcomp8);
add(jcomp9);
// set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds(15, 10, 595, 350);
jcomp2.setBounds(35, 375, 100, 25);
jcomp3.setBounds(190, 375, 100, 25);
jcomp4.setBounds(320, 375, 100, 25);
jcomp5.setBounds(465, 375, 100, 25);
jcomp6.setBounds(35, 450, 100, 25);
jcomp7.setBounds(190, 450, 100, 25);
jcomp8.setBounds(320, 450, 100, 25);
jcomp9.setBounds(465, 450, 100, 25);
}
class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("1")) {
jcomp1.set(image1);
}
}
}
public static void main (String[] args) {
JFrame frame = new JFrame("MyPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyPanel());
frame.pack();
frame.setVisible (true);
}
}
I believe you are trying to get something like this:
public class MyPanel extends JPanel {
private JLabel label;
private JButton[] buttons = new JButton[8];
private ImageIcon[] images = new ImageIcon[8];
public MyPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(2, 4, 15, 10));
for (int i = 0; i < images.length; i++) {
images[i] = new ImageIcon(getClass().getResource(i+1 + ".png"));
buttons[i] = new JButton(String.valueOf(i+1));
buttons[i].setActionCommand(String.valueOf(i+1));
buttons[i].addActionListener(new ButtonClickListener());
buttonPanel.add(buttons[i]);
}
label = new JLabel(images[0]);
setLayout(new BorderLayout());
add(label);
add(buttonPanel, BorderLayout.PAGE_END);
}
class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setIcon(images[Integer.parseInt(e.getActionCommand()) - 1]);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("MyPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyPanel());
frame.pack();
frame.setVisible(true);
}
}
Notes:
Don't forget to change the image file name.
You can play with the layout manager to get what you want.
I removed setPreferredSize(new Dimension(624, 537)); because you didn't specify a resize behavior which would make this line meaningless. pack() would take care of the sizes for you.
Set the icon of the button or label. To do this, you need to create an ImageIcon, which has multiple constructors to create from a filename or a loaded image.
jcomp1.setIcon(new ImageIcon(...));
Related
I've been making an app with java swing and JavaFX and didn't run into a problem until now. Whenever I set the guis visibility to true, the GUI becomes very small, when it should be 1150 px wide, 900 px tall. Does anyone get any ideas?
Main Gui code:
import javax.swing.*;
import java.awt.*;
public class mainGui extends JFrame{
public static JFrame mainScreen = new JFrame("Tamo");
public mainGui() {
JPanel topPanel = new JPanel();
mainScreen.setSize(1150, 900);
mainScreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainScreen.setResizable(false);
mainScreen.setLayout(new BorderLayout());
topPanel.setBackground(new Color(226, 230, 204));
topPanel.setPreferredSize(new Dimension(1150, 100));
mainScreen.add(topPanel, BorderLayout.NORTH);
ImageIcon icon = new ImageIcon("C:\\Users\\uname\\Desktop\\TamoDienynas\\pngs\\tamo.png");
mainScreen.setIconImage(icon.getImage());
mainScreen.setVisible(false);
}
public static void main(String[] args) {
new mainGui();
}
}
Class which make's the gui visible:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static me.rockorbonk.tamodienynas.GUI.mainGui.mainScreen;
public class loginGui extends JFrame implements ActionListener {
private static JFrame frame;
private static JLabel userLabel;
private static JLabel passwordLabel;
private static JLabel success;
private static JButton login;
private static JTextField userText;
private static JPasswordField passwordText;
loginGui() {
frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(panel);
panel.setLayout(null);
userLabel = new JLabel("User");
userLabel.setBounds(10, 20, 80, 25);
panel.add(userLabel);
userText = new JTextField();
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
passwordText = new JPasswordField();
passwordText.setBounds(100, 50, 165, 25);
panel.add(passwordText);
login = new JButton("Login");
login.setBounds(10, 80, 80, 25);
login.addActionListener(this);
panel.add(login);
success = new JLabel("");
success.setBounds(10, 110, 300, 25);
panel.add(success);
ImageIcon icon = new ImageIcon("C:\\Users\\uname\\Desktop\\TamoDienynas\\pngs\\tamo.png");
frame.setIconImage(icon.getImage());
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae) {
String uname = userText.getText();
String pwd = passwordText.getText();
if(uname.equals("rokasbruz") && pwd.equals("Rokas123")) {
success.setText("Sekmingai prisijungėte!");
ActionListener l = evt -> {
userLabel.setVisible(false);
passwordLabel.setVisible(false);
userText.setVisible(false);
passwordText.setVisible(false);
login.setVisible(false);
success.setVisible(false);
frame.setVisible(false);
mainScreen.setVisible(true);
mainScreen.pack();
};
Timer timer = new Timer(2000, l);
timer.setRepeats(false);
timer.start();
}
else{
success.setText("Slapyvardis arba slaptažodis nesutampa!");
}
}
public static void main(String[] args) {
new loginGui();
}
}
Any help would be appreciated!
P.S. I'm using IntelliJ ultimate as the IDE
-Rock
mainScreen is just a JFrame that does not contain anything. Hence when you make it visible, all you see is the title bar. In order to initialize mainScreen you need to call mainGui constructor. Nonetheless, as Andrew Thompson wrote in his comment, your style of coding a Swing application is very unusual. Consider using a dialog as your login window.
Here is your code that displays mainScreen as I believe you intended. I only changed the ActionListener, in class loginGui, that displays mainGui. I added one line which is indicated with the comment ADDED THIS LINE
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.Timer;
import static me.rockorbonk.tamodienynas.GUI.mainGui.mainScreen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class loginGui extends JFrame implements ActionListener {
private static JFrame frame;
private static JLabel userLabel;
private static JLabel passwordLabel;
private static JLabel success;
private static JButton login;
private static JTextField userText;
private static JPasswordField passwordText;
loginGui() {
frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(panel);
panel.setLayout(null);
userLabel = new JLabel("User");
userLabel.setBounds(10, 20, 80, 25);
panel.add(userLabel);
userText = new JTextField();
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
passwordText = new JPasswordField();
passwordText.setBounds(100, 50, 165, 25);
panel.add(passwordText);
login = new JButton("Login");
login.setBounds(10, 80, 80, 25);
login.addActionListener(this);
panel.add(login);
success = new JLabel("");
success.setBounds(10, 110, 300, 25);
panel.add(success);
ImageIcon icon = new ImageIcon("C:\\Users\\uname\\Desktop\\TamoDienynas\\pngs\\tamo.png");
frame.setIconImage(icon.getImage());
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae) {
String uname = userText.getText();
String pwd = passwordText.getText();
if (uname.equals("rokasbruz") && pwd.equals("Rokas123")) {
success.setText("Sekmingai prisijungėte!");
ActionListener l = evt -> {
userLabel.setVisible(false);
passwordLabel.setVisible(false);
userText.setVisible(false);
passwordText.setVisible(false);
login.setVisible(false);
success.setVisible(false);
frame.setVisible(false);
new mainGui(); // ADDED THIS LINE
mainScreen.setVisible(true);
mainScreen.pack();
};
Timer timer = new Timer(2000, l);
timer.setRepeats(false);
timer.start();
}
else {
success.setText("Slapyvardis arba slaptažodis nesutampa!");
}
}
public static void main(String[] args) {
new loginGui();
}
}
Here is how it appears (after logging in).
This question already has an answer here:
Java aligning components in panels
(1 answer)
Closed 6 years ago.
I add a JTextField to my game in the bottom left corner using a nested BorderLayout inside my main panel's BorderLayout.SOUTH. This works fine, but then when I add a button to go right next to it, my JTextField dissapears. Can someone please help?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BlackjackGUI{
private JFrame frame;
private JPanel panel, panelLeft, panelBottom;
private JButton newGameBtn, dealBtn, hitBtn, standBtn;
private JLabel placeBetLbl, playerMoneyLbl;
private JLabel playerCard1Lbl, playerCard2Lbl, playerCard3Lbl,
playerCard4Lbl, playerCard5Lbl, playerCard6Lbl, playerCard7Lbl;
private JLabel dealerCard1Lbl, dealerCard2Lbl, dealerCard3Lbl, dealerCard4Lbl,
dealerCard5Lbl, dealerCard6Lbl, dealerCard7Lbl;
private JLabel playerCardValueLbl, dealerCardValueLbl;
private JLabel spacer1, spacer2;
private JTextField betInputBox;
public BlackjackGUI(){
createForm();
addTextField();
addButtons();
addLabels();
frame.add(panel);
frame.setVisible(true);
}
public void createForm() {
frame = new JFrame("Blackjack");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200,800);
panel = new JPanel();
panel.setLayout(new BorderLayout());
Color c = new Color(0, 100, 0);
panel.setBackground(c);
panelLeft = new JPanel();
Color panelLeftBG = new Color (23, 25, 100);
panelLeft.setBackground(panelLeftBG);
panel.add(panelLeft, BorderLayout.WEST);
panelBottom = new JPanel();
Color panelBottomBG = new Color (56, 12, 10);
panelBottom.setBackground(panelBottomBG);
panelBottom.setLayout(new BorderLayout());
panel.add(panelBottom, BorderLayout.SOUTH);
}
public void addButtons() {
newGameBtn = new JButton("New Game");
panelLeft.add(newGameBtn, BorderLayout.WEST);
newGameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
dealBtn = new JButton("Deal");
dealBtn.setPreferredSize(new Dimension (100, 50));
panelBottom.add(dealBtn, BorderLayout.WEST);
newGameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
public void addTextField() {
betInputBox = new JTextField("£25.00");
betInputBox.setFont(new Font("Gill Sans MT", Font.PLAIN, 35));
betInputBox.setHorizontalAlignment(SwingConstants.RIGHT);
betInputBox.setPreferredSize(new Dimension(175,50));
panelBottom.add(betInputBox, BorderLayout.WEST);
}
public void addLabels() {
placeBetLbl = new JLabel("Place your bets!");
placeBetLbl.setFont(new Font("Gill Sans MT", Font.PLAIN, 35));
panelBottom.add(placeBetLbl);
playerMoneyLbl = new JLabel("£2,500");
playerMoneyLbl.setFont(new Font("Gill Sans MT", Font.PLAIN, 35));
panelBottom.add(playerMoneyLbl, BorderLayout.EAST);
}
public static void main(String[] args) {
new BlackjackGUI();
}
}
Excerpt from the BorderLayout javadoc:
Each region may contain no more than one component, and is identified
by a corresponding constant: NORTH, SOUTH, EAST, WEST, and
CENTER.
Your are first adding the text field and then the button to the same region (WEST), thus button just replaces the text field.
To solve the issue you can use FlowLayout for the panelBottom:
panelBottom.setLayout(new FlowLayout(FlowLayout.LEFT));
The gui has five buttons, and a default image. I would like the image to change when each of the buttons is pressed. I have tried this for 'pink' by updating the path but I am at loss as to what needs to be done each time.
public class PikminGui extends JFrame{
private JPanel buttons;
private JLabel title;
private JButton grow;
private JButton pink;
private JButton black;
private JButton blue;
private JButton red;
private JButton yellow;
private JFrame f;
private JLabel label;
private JPanel panel;
public String path;
public PikminGui() {
createGui();
}
public void createGui() {
path = "path-to-image1";
f = new JFrame();
panel = new JPanel(new BorderLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setLocation(200,200);
f.setVisible(true);
title = new JLabel("PIKMIN MAKER", JLabel.CENTER);
panel.add(title,BorderLayout.NORTH);
grow = new JButton("Grow");
grow.setBorder(BorderFactory.createRaisedBevelBorder());
panel.add(grow,BorderLayout.WEST);
buttons = new JPanel();
pink = new JButton("Pink");
pink.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
path = "path-to-image2";
}
});
black = new JButton("Black");
yellow = new JButton("Yellow");
blue = new JButton("Blue");
red = new JButton("Red");
buttons.setLayout(new FlowLayout());
buttons.add(pink);
buttons.add(black);
buttons.add(yellow);
buttons.add(blue);
buttons.add(red);
panel.add(buttons,BorderLayout.SOUTH);
File file = new File(path);
BufferedImage image;
try {
image = ImageIO.read(file);
label = new JLabel(new ImageIcon(image));
panel.add(label, BorderLayout.CENTER );
f.getContentPane().add(panel);
f.pack();
f.add(panel);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have a JLabel with an ImageIcon that isn't showing.
public class Lockscreen extends JFrame {
JPanel layer;
JButton signin;
ImageIcon heartlock;
String heartlockpath;
JLabel heartlockdisplay;
String arrowpath;
public Lockscreen(){
super("Startseite");
setSize(700, 400);
setLocation(100, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
arrowpath = "C:\\Users\\saydanan\\Pictures\\FürMyDiary\\Right_Arrow.png";
signin = new JButton();
signin.setSize(19, 12);
signin.setIcon(new ImageIcon(arrowpath));
signin.setLocation(250, 500);
heartlockpath = "C:\\Users\\saydananPicturesFürMyDiary\\082326-green-jelly-icon-business-lock-heart.png";
heartlock = new ImageIcon(heartlockpath);
heartlockdisplay = new JLabel();
heartlockdisplay.setIcon(heartlock);
heartlockdisplay.setLocation(250, 250);
heartlockdisplay.setSize(heartlock.getIconWidth(), heartlock.getIconHeight());
heartlockdisplay.setVisible(true);
layer = new JPanel();
layer.setBackground(Color.black);
/*layer.setLayout(...);*/
addEverything(layer);
getContentPane().add(layer);
setVisible(true);
}
public void addEverything(JPanel panel){
panel.add(signin);
panel.add(heartlockdisplay);
panel.repaint();
}
}
You need to add it, and then set it to be visible.
As in:
panel.add(heartlockdisplay);
heartlockdisplay.setVisible(true);
panel.setVisible(true);
I'm putting together the basic layout for a contacts book, and I want to know how I can make the 3 test buttons span from edge to edge just as the arrow buttons do.
private static class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Code Placeholder");
}
}
public static void main(String[] args) {
//down button
ImageIcon downArrow = new ImageIcon("down.png");
JButton downButton = new JButton(downArrow);
ButtonHandler downListener = new ButtonHandler();
downButton.addActionListener(downListener);
//up button
ImageIcon upArrow = new ImageIcon("up.png");
JButton upButton = new JButton(upArrow);
ButtonHandler upListener = new ButtonHandler();
upButton.addActionListener(upListener);
//contacts
JButton test1Button = new JButton("Code Placeholder");
JButton test2Button = new JButton("Code Placeholder");
JButton test3Button = new JButton("Code Placeholder");
Box box = Box.createVerticalBox();
box.add(test1Button);
box.add(test2Button);
box.add(test3Button);
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(box, BorderLayout.CENTER);
content.add(downButton, BorderLayout.SOUTH);
content.add(upButton, BorderLayout.NORTH);
JFrame window = new JFrame("Contacts");
window.setContentPane(content);
window.setSize(400, 600);
window.setLocation(100, 100);
window.setVisible(true);
}
Following up on #kloffy's suggestion:
package playground.tests;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import junit.framework.TestCase;
public class ButtonTest extends TestCase {
public void testThreeButtons() throws Exception {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout());
JButton button1 = new JButton("A");
JButton button2 = new JButton("B");
JButton button3 = new JButton("C");
panel.add(button1);
panel.add(button2);
panel.add(button3);
JFrame window = new JFrame("Contacts");
window.setContentPane(panel);
window.setSize(300, 600);
window.pack();
window.setVisible(true);
int width = button1.getWidth();
assertEquals(width, button2.getWidth());
assertEquals(width, button3.getWidth());
}
}