Change the background in JFrame - java

I'm getting the Co-ordinates of the mouse on the window , I'm also changing the background color using KeyListner
Letter B for Black
W for White
G for green
.......
but when I change the background color , only the background of the label is changing and not the entire window ,what I need is to change the entire window and not just the label , any ideas why is that ?
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class mouseCrd extends JFrame {
private JPanel contentPane;
public mouseCrd() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 650);
setTitle("Mouse co-ordinates");
setVisible(true);
setResizable(false);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 650, 650);
contentPane.add(panel);
JLabel label = new JLabel(".................");
label.setFont(new Font("Tahoma", Font.BOLD, 30));
panel.add(label);
panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
label.setText("X = "+ e.getX()+" ; Y = "+e.getY());
}
});
addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
int clr = e.getKeyChar();
if(clr==KeyEvent.VK_B)
{
System.out.println("B is pressed");
label.setOpaque(true);
label.setBackground(Color.BLACK);
add(label);
}
else if(clr==KeyEvent.VK_W)
{
System.out.println("B is pressed");
label.setOpaque(true);
label.setBackground(Color.WHITE);
add(label);
}
else if(clr==KeyEvent.VK_R)
{
System.out.println("B is pressed");
label.setOpaque(true);
label.setBackground(Color.RED);
add(label);
}
else if(clr==KeyEvent.VK_O)
{
System.out.println("B is pressed");
label.setOpaque(true);
label.setBackground(Color.ORANGE);
add(label);
}
else if(clr==KeyEvent.VK_G)
{
System.out.println("B is pressed");
label.setOpaque(true);
label.setBackground(Color.GREEN);
add(label);
}
}
});
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable()
{
public void run() {
try {
mouseCrd frame = new mouseCrd();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}

if you want to change the background of your aplication, you have to change the background of the JPane that contains all your components, you are doing:
label.setBackground(Color.ORANGE);
which is okay if you want to change the background of the label, this is explicit on the instruction, i did some changes in your code, look at this:
public class mouseCrd extends JFrame {
public mouseCrd() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 650);
setTitle("Mouse co-ordinates");
setVisible(true);
setResizable(false);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 650, 650);
add(panel);
JLabel label = new JLabel(".................");
label.setFont(new Font("Tahoma", Font.BOLD, 30));
panel.add(label);
panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
label.setText("X = "+ e.getX()+" ; Y = "+e.getY());
}
});
addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
char keyPressed = e.getKeyChar();
if(keyPressed=='b')
{
System.out.println("B is pressed");
panel.setBackground(Color.BLACK);
}
else if(keyPressed=='w')
{
System.out.println("W is pressed");
panel.setBackground(Color.WHITE);
}
else if(keyPressed=='r')
{
System.out.println("R is pressed");
panel.setBackground(Color.RED);
}
else if(keyPressed=='o')
{
System.out.println("O is pressed");
panel.setBackground(Color.ORANGE);
}
else if(keyPressed=='g')
{
System.out.println("G is pressed");
panel.setBackground(Color.GREEN);
}
}
});
}
public static void main(String[] args){
new mouseCrd();
}
}
I removed the contentPane because it was useless an then in the key released, i just change the backgound of the panel JPane with the method setBackground(), and i removed the use of the KeyEvent constants because is easier to use chars

I know what you already get the needed answer, but I would like to recommend you the Oracle Documentation regarding Swing and GUI's.
Its begginer friendly 😁 and it stress exactly what you need to know to have good fundaments.
https://docs.oracle.com/javase/tutorial/uiswing/index.html

Related

Set JPanel transparent for keypad

I'm actually codding a keypad for an application and I'm encountering a problem. I'm using some empty space in the JDialog I'm creating to place an exist button on the top right corner of the Dialog box. This empty space is creating a border to the dialog box which is unpleasant to see. So I've tried to make panels transparent with setOpaque(false) function, but I achieved nothing. Do I have to use the paint function (which I don't know how to use) ?
Here is my test function without the setOpaque tests I've done :
package test;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class Test {
public static JFrame frame;
public static void main(String args[]){
frame = new JFrame();
JPanel panel = new JPanel();
panel.setSize(400, 400);
panel.setBackground(Color.CYAN);
panel.setLayout(new GridBagLayout());
JTextField text = new JTextField("coucou");
panel.add(text);
text.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
text.setText("");
openKeypad(text);
}
});
frame.setContentPane(panel);
frame.setSize(400, 400);
frame.setUndecorated(true);
frame.setLocation(50,0);
frame.setVisible(true);
}
private static void openKeypad(JTextField text) {
KeyPad pad = new KeyPad(frame, text);
}
}
KeyPad class :
package test;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class KeyPad extends JDialog {
private JTextField field;
public KeyPad(JFrame parent, JTextField field_) {
super(parent, true);
//Initializing field
field = field_;
//Setting layout
JPanel panelButton = new JPanel();
panelButton.setLayout(new GridLayout(4, 3));
//Buttons declaration
JButton b0 = new JButton("0");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton bp = new JButton(".");
JButton del = new JButton();
JButton close = new JButton();
//Setting buttons icons
try {
Image img = ImageIO.read(new File("ressources/closeIcon.png"));
close.setIcon(new ImageIcon(img));
img = ImageIO.read(new File("ressources/deleteIcon.png"));
del.setIcon(new ImageIcon(img));
close.setOpaque(false);
close.setBorder(new EmptyBorder(0, 0, 0, 0));
close.setContentAreaFilled(false);
}catch (Exception e) {
System.out.println(e);
}
//Buttons sizing
b0.setPreferredSize(new Dimension(64, 64));
b1.setPreferredSize(new Dimension(64, 64));
b2.setPreferredSize(new Dimension(64, 64));
b3.setPreferredSize(new Dimension(64, 64));
b4.setPreferredSize(new Dimension(64, 64));
b5.setPreferredSize(new Dimension(64, 64));
b6.setPreferredSize(new Dimension(64, 64));
b7.setPreferredSize(new Dimension(64, 64));
b8.setPreferredSize(new Dimension(64, 64));
b9.setPreferredSize(new Dimension(64, 64));
bp.setPreferredSize(new Dimension(64, 64));
del.setPreferredSize(new Dimension(64, 64));
close.setPreferredSize(new Dimension(32, 32));
//Adding buttons to the panelButton
panelButton.add(b7);
panelButton.add(b8);
panelButton.add(b9);
panelButton.add(b4);
panelButton.add(b5);
panelButton.add(b6);
panelButton.add(b1);
panelButton.add(b2);
panelButton.add(b3);
panelButton.add(bp);
panelButton.add(b0);
panelButton.add(del);
//Adding Listeners
b0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('0');
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('1');
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('2');
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('3');
}
});
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('4');
}
});
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('5');
}
});
b6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('6');
}
});
b7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('7');
}
});
b8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('8');
}
});
b9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('9');
}
});
bp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('.');
}
});
del.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
delDigit();
}
});
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
disposeDialog();
}
});
//Placing close button
JPanel panelClose = new JPanel();
panelClose.setLayout(new BoxLayout(panelClose, BoxLayout.X_AXIS));
panelClose.add(Box.createRigidArea(new Dimension(64*3, 1)));
panelClose.add(close);
JPanel test = new JPanel();
test.setLayout(new BoxLayout(test, BoxLayout.X_AXIS));
test.add(panelButton);
test.add(Box.createRigidArea(new Dimension(32, 1)));
//Setting main panel
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(panelClose);
panel.add(test);
//Setting and displaying the Dialog Box
this.setContentPane(panel);
this.setUndecorated(true);
this.pack();
this.setVisible(true);
}
private void addDigit(char i) {
field.setText(field.getText() + i);
}
private void delDigit() {
if(field.getText().length() > 0) {
field.setText(field.getText().substring(0, field.getText().length() - 1));
}
}
private void disposeDialog() {
this.dispose();
}
}
/////EDIT///////
Here is my keypad code at the moment if someone wants to use it, feel free.
package mainPackage;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class KeyPad extends JDialog {
private GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
private GraphicsDevice[] gs = ge.getScreenDevices();
private JTextField field;
public KeyPad(JDialog parent, JTextField field_, String placement) {
super(parent, true);
//Initializing field
field = field_;
//Setting layout
JPanel panelButton = new JPanel();
panelButton.setLayout(new GridLayout(4, 3));
//Buttons declaration
JButton b0 = new JButton("0");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton bp = new JButton(".");
JButton del = new JButton();
JButton close = new JButton();
//Setting buttons icons
try {
Image img = ImageIO.read(new File("ressources/closeIcon.png"));
close.setIcon(new ImageIcon(img));
img = ImageIO.read(new File("ressources/deleteIcon.png"));
del.setIcon(new ImageIcon(img));
close.setOpaque(false);
close.setBorder(new EmptyBorder(0, 0, 0, 0));
close.setContentAreaFilled(false);
}catch (Exception e) {
System.out.println(e);
}
//Buttons sizing
b0.setPreferredSize(new Dimension(64, 64));
b1.setPreferredSize(new Dimension(64, 64));
b2.setPreferredSize(new Dimension(64, 64));
b3.setPreferredSize(new Dimension(64, 64));
b4.setPreferredSize(new Dimension(64, 64));
b5.setPreferredSize(new Dimension(64, 64));
b6.setPreferredSize(new Dimension(64, 64));
b7.setPreferredSize(new Dimension(64, 64));
b8.setPreferredSize(new Dimension(64, 64));
b9.setPreferredSize(new Dimension(64, 64));
bp.setPreferredSize(new Dimension(64, 64));
del.setPreferredSize(new Dimension(64, 64));
close.setPreferredSize(new Dimension(32, 32));
//Adding buttons to the panelButton
panelButton.add(b7);
panelButton.add(b8);
panelButton.add(b9);
panelButton.add(b4);
panelButton.add(b5);
panelButton.add(b6);
panelButton.add(b1);
panelButton.add(b2);
panelButton.add(b3);
panelButton.add(bp);
panelButton.add(b0);
panelButton.add(del);
panelButton.setOpaque(false);
//Adding Listeners
b0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('0');
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('1');
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('2');
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('3');
}
});
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('4');
}
});
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('5');
}
});
b6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('6');
}
});
b7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('7');
}
});
b8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('8');
}
});
b9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('9');
}
});
bp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('.');
}
});
del.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
delDigit();
}
});
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
disposeDialog();
}
});
//Placing close button
JPanel panelClose = new JPanel();
panelClose.setLayout(new BoxLayout(panelClose, BoxLayout.X_AXIS));
panelClose.add(Box.createRigidArea(new Dimension(64*3, 1)));
panelClose.add(close);
panelClose.setOpaque(false);
JPanel panelButtonWithPadding = new JPanel();
panelButtonWithPadding.setLayout(new BoxLayout(panelButtonWithPadding, BoxLayout.X_AXIS));
panelButtonWithPadding.add(panelButton);
panelButtonWithPadding.add(Box.createRigidArea(new Dimension(32, 1)));
panelButtonWithPadding.setOpaque(false);
//Setting main panel
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(panelClose);
panel.add(panelButtonWithPadding);
panel.setOpaque(false);
//Setting dialog box transparency
panelButton.setOpaque(false);
panelClose.setOpaque(false);
panelButtonWithPadding.setOpaque(false);
panel.setOpaque(false);
//Setting and displaying the Dialog Box
this.setContentPane(panel);
this.setUndecorated(true);
this.setBackground( new Color(0, 0, 0, 0) ); // set transparency on JDialog only
this.pack();
//To place the KeyPad anywhere on the panel
switch(placement) {
case "BOTTOM_LEFT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x, 600 - (int) this.getSize().getHeight());
break;
case "BOTTOM_CENTER":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) ((800 - this.getSize().getWidth())/2) , 600 - (int) this.getSize().getHeight());
break;
case "BOTTOM_RIGHT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) (800 - this.getSize().getWidth()), 600 - (int) this.getSize().getHeight());
break;
case "CENTER_LEFT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x, (int) (600 - this.getSize().getHeight())/2);
break;
case "CENTER":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) ((800 - this.getSize().getWidth())/2), (int) (600 - this.getSize().getHeight())/2);
break;
case "CENTER_RIGHT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) (800 - this.getSize().getWidth()), (int) (600 - this.getSize().getHeight())/2);
break;
case "TOP_LEFT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x, 0);
break;
case "TOP_CENTER":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) ((800 - this.getSize().getWidth())/2), 0);
break;
case "TOP_RIGHT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) (800 - this.getSize().getWidth()), 0);
break;
}
this.setVisible(true);
}
private void addDigit(char i) {
field.setText(field.getText() + i);
}
private void delDigit() {
if(field.getText().length() > 0) {
field.setText(field.getText().substring(0, field.getText().length() - 1));
}
}
private void disposeDialog() {
this.dispose();
}
}
Simple example for making a JFrame transparent:
import java.awt.*;
import static java.awt.GraphicsDevice.WindowTranslucency.TRANSLUCENT;
import javax.swing.*;
class TransparentFrame extends JFrame
{
public TransparentFrame()
{
JPanel panel = new JPanel();
panel.setOpaque( false );
panel.add( new JButton("Button") );
add(panel, BorderLayout.SOUTH);
setUndecorated(true);
setSize(300, 300);
//pack();
// setOpacity(0.5f); // set transparency on frame and components
setBackground( new Color(0, 0, 0, 64) ); // set transparency on frame only
setTitle("Transparent Frame Demo");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public static void main(String args[])
{
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
// Exit when translucent windows aren't supported
if (!gd.isWindowTranslucencySupported(TRANSLUCENT))
{
System.err.println( "Translucency is not supported" );
System.exit(0);
}
// Create the GUI on the event-dispatching thread
SwingUtilities.invokeLater(() -> new TransparentFrame().setVisible(true));
}
}

Position Not Moving Despite of Key Listener

I made the Card Layout Working completely fine but what happened now is I added a keylistener to the object character which is a JLabel so whenever the person presses up the character should move up but it does absolutely nothing!
I also tried replacing it with a button which moves it when clicked and it worked completely fine. Also I tried changing the event meaning I changed that if they press up then the image of the town map would change but still no effect so it seems there is something wrong with my KeyListener
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.*;
import javax.swing.*;
#SuppressWarnings({ "unused", "serial" })
public class FinalBlowzXC extends JFrame implements KeyListener{
public static JPanel game=new JPanel();
public static JPanel mainmenu=new JPanel(null);
public static JPanel loginpanel=new JPanel(null);
public static JPanel tutorial=new JPanel(null);
public static JPanel registration=new JPanel(null);
public static JPanel town_map=new JPanel(null);
public JTextField username= new JTextField("Username");
public JTextField password=new JTextField("Password");
public JLabel bglogin=new JLabel();
public JLabel character=new JLabel();
public JButton log_in=new JButton();
public JButton register=new JButton();
CardLayout page= new CardLayout();
public String level="";
public int charx=350;
public int chary=435;
public static void main(String []args)
{
new FinalBlowzXC().setVisible(true);
}
public FinalBlowzXC()
{
super("Final Blowz Xchanged");
setSize(640,510);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
game.setLayout(page);
game.add(mainmenu, "1");
game.add(loginpanel, "2");
game.add(tutorial, "3");
game.add(registration, "4");
game.add(town_map, "5");
add(game);
opening();
}
public void opening()
{
page.show(game, "1");
JLabel bgmainmenu;
JButton start;
JButton exit;
bgmainmenu = new JLabel();
start = new JButton();
exit = new JButton();
bgmainmenu.setIcon(new ImageIcon(getClass().getResource("/FF-XV.jpg")));
bgmainmenu.setBounds(0,0,640,480);
mainmenu.add(bgmainmenu);
mainmenu.add(start);
start.setBounds(280, 360, 70, 20);
start.setBorder(null);
start.setBorderPainted(false);
start.setContentAreaFilled(false);
start.setOpaque(false);
start.addActionListener(new Start());
exit.setBounds(280, 385, 70, 20);
mainmenu.add(exit);
exit.setBorder(null);
exit.setBorderPainted(false);
exit.setContentAreaFilled(false);
exit.setOpaque(false);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
class Start implements ActionListener{
public void actionPerformed(ActionEvent e) {
login();
}
}
public void login()
{
page.show(game, "2");
bglogin.setIcon(new ImageIcon(getClass().getResource("/FF-XV Login.jpg")));
bglogin.setBounds(0, 0, 640, 480);
username.setBounds(300, 285, 85, 15);
username.setBorder(null);
username.setForeground(Color.WHITE);
username.setOpaque(false);
password.setBounds(300, 310, 85, 20);
password.setBorder(null);
password.setForeground(Color.WHITE);
password.setOpaque(false);
log_in.setBounds(280, 335, 50, 45);
log_in.setBorder(null);
log_in.setBorderPainted(false);
log_in.setContentAreaFilled(false);
log_in.setOpaque(false);
log_in.addActionListener(new Log_in());
register.setBounds(335, 335, 55, 45);
register.setBorder(null);
register.setBorderPainted(false);
register.setContentAreaFilled(false);
register.setOpaque(false);
register.addActionListener(new Register());
loginpanel.add(username);
loginpanel.add(password);
loginpanel.add(bglogin);
loginpanel.add(log_in);
loginpanel.add(register);
}
class Log_in implements ActionListener{
public void actionPerformed(ActionEvent e)
{
Tutorial();
}
}
class Register implements ActionListener{
public void actionPerformed(ActionEvent e)
{
page.show(game, "4");
}
}
public void Tutorial()
{
page.show(game, "3");
JLabel bgtutorial=new JLabel();
JLabel animeforward=new JLabel();
JLabel animeright=new JLabel();
JLabel animeleft=new JLabel();
JButton next=new JButton();
JLabel animebackward=new JLabel();
bgtutorial.setIcon(new ImageIcon(getClass().getResource("/FF-XV Tutorial.jpg")));
bgtutorial.setBounds(0, 0, 640, 480);
animeforward.setIcon(new ImageIcon(getClass().getResource("walkanimofficialfront.gif")));
animeforward.setBounds(115, 230, 30, 30);
animeright.setIcon(new ImageIcon(getClass().getResource("walkanimofficialright.gif")));
animeright.setBounds(190, 315, 30, 30);
animeleft.setIcon(new ImageIcon(getClass().getResource("walkanimofficialleft.gif")));
animeleft.setBounds(45, 315, 30, 30);
animebackward.setIcon(new ImageIcon(getClass().getResource("walkanimofficialback.gif")));
animebackward.setBounds(115, 405, 30, 30);
next.setBounds(530, 430, 100, 30);
next.setBorder(null);
next.setBorderPainted(false);
next.setContentAreaFilled(false);
next.setOpaque(false);
next.addActionListener(new Next());
tutorial.add(next);
tutorial.add(animeright);
tutorial.add(animeleft);
tutorial.add(animebackward);
tutorial.add(animeforward);
tutorial.add(bgtutorial);
}
class Next implements ActionListener{
public void actionPerformed(ActionEvent e)
{
town();
}
}
public void town()
{
page.show(game, "5");
JLabel map=new JLabel();
map.setIcon(new ImageIcon(getClass().getResource("/FF-XV Town.jpg")));
map.setBounds(0, 0, 640, 480);
character.setIcon(new ImageIcon(getClass().getResource("standfront.png")));
character.setBounds(charx, chary, 30, 35);
town_map.add(character);
town_map.add(map);
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_UP)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialfront.gif")));
character.setLocation(character.getX(), character.getY()+5);
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialright.gif")));
character.setLocation(character.getX()+5, character.getY());
}
if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialleft.gif")));
character.setLocation(character.getX()-5, character.getY()+5);
}
if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialback.gif")));
character.setLocation(character.getX(), character.getY()-5);
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
Add following code in your programme.
public static JPanel mainmenu = new JPanel();
public static JPanel loginpanel = new JPanel();
or initialize mainmenu & loginpanel before adding them into the game panel.
when you call game.add(loginPanel, "2") loginPanel is null

Setting Action Listener and changing background

I've created 3 buttons. They are each displayed twice in a JFrame. I'm having trouble changing the background of the frame. I've set ActionListeners but upon clicking, nothing is changing. May I ask for some help.
public class MyButtons extends JPanel {
public static JFrame frame;
private JButton Red = new JButton("Red");
private JButton Green = new JButton("Green");
private JButton Blue = new JButton("Blue");
public void InitializeButton()
{
Blue.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setBackground(Color.BLUE);
}
});
Green.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setBackground(Color.GREEN);
}
});
Red.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setBackground(Color.RED);
}
});
}
public MyButtons() {
InitializeButton();
add(Red);
add(Green);
add(Blue);
}
public static void main(String[] args) {
frame = new JFrame();
JPanel row1 = new MyButtons();
JPanel row2 = new MyButtons();
row1.setPreferredSize(new Dimension(250, 100));
row2.setPreferredSize(new Dimension(250, 100));
frame.setLayout(new GridLayout(3,2));
frame.add(row1);
frame.add(row2);
frame.pack();
frame.setVisible(true);
}
}
This code works, but probably not as you expected:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyButtons extends JPanel {
//public static JFrame frame;
// static is rarely a solution of problems in a GUI. ToDo! Change!
static JPanel ui = new JPanel(new GridLayout(2, 0, 20, 20));
private JButton Red = new JButton("Red");
private JButton Green = new JButton("Green");
private JButton Blue = new JButton("Blue");
public void InitializeButton() {
Blue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.BLUE);
}
});
Green.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.GREEN);
}
});
Red.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.RED);
}
});
}
public MyButtons() {
InitializeButton();
add(Red);
add(Green);
add(Blue);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 100);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel row1 = new MyButtons();
JPanel row2 = new MyButtons();
//row1.setPreferredSize(new Dimension(250, 100));
//row2.setPreferredSize(new Dimension(250, 100));
//frame.setLayout(new GridLayout(3, 2,10,10));
ui.add(row1);
ui.add(row2);
frame.add(ui);
frame.pack();
frame.setVisible(true);
}
}
N.B. Please learn common Java nomenclature (naming conventions - e.g. EachWordUpperCaseClass, firstWordLowerCaseMethod(), firstWordLowerCaseAttribute unless it is an UPPER_CASE_CONSTANT) and use it consistently.

Java- disable buttons on one jpanel with another.

So my goal is to disable buttons on lets say panel B depending one what button they press on panel A. so below I have 2 combo boxes that id like to be able to enable or disable base on the buttons pressed on the first panel. Ive tried googling this problem but I'm new to java so its pretty rough going so far.
heres my sample code of what I'm trying to do.
package pack2;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
public class tessst {
public boolean enableChk1;
public boolean enableChk2;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tessst window = new tessst();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public tessst() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel panel = new JPanel();
frame.getContentPane().add(panel, "name_15095567731094");
panel.setLayout(null);
final JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, "name_15101078033315");
panel_1.setLayout(null);
JButton select2 = new JButton("2 boxes");
select2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
enableChk2 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
}
});
select2.setBounds(276, 101, 89, 23);
panel.add(select2);
JButton select1 = new JButton("1 boxes");
select1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
}
});
select1.setBounds(59, 101, 89, 23);
panel.add(select1);
JButton select0 = new JButton("no boxes");
select0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = false;
enableChk2 = false;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
}
});
select0.setBounds(166, 169, 89, 23);
panel.add(select0);
JComboBox comboBox = new JComboBox();
comboBox.setEnabled(enableChk1);
comboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox.setBounds(52, 100, 61, 20);
panel_1.add(comboBox);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setEnabled(enableChk2);
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox_1.setBounds(265, 100, 79, 20);
panel_1.add(comboBox_1);
JButton back = new JButton("go back");
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.setVisible(true);
panel_1.setVisible(false);
}
});
back.setBounds(10, 227, 89, 23);
panel_1.add(back);
}
}
I needed to declare my comboBox's above my buttons then declare them as final.
here are the changes
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class tessst {
public boolean enableChk1;
public boolean enableChk2;
JComboBox comboBox;
JComboBox comboBox_1;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tessst window = new tessst();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public tessst() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel panel = new JPanel();
frame.getContentPane().add(panel, "name_15095567731094");
panel.setLayout(null);
final JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, "name_15101078033315");
panel_1.setLayout(null);
JButton select2 = new JButton("2 boxes");
select2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
enableChk2 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
comboBox.setEnabled(true);
comboBox_1.setEnabled(true);
}
});
select2.setBounds(276, 101, 89, 23);
panel.add(select2);
JButton select1 = new JButton("1 boxes");
select1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
comboBox.setEnabled(true);
}
});
select1.setBounds(59, 101, 89, 23);
panel.add(select1);
JButton select0 = new JButton("no boxes");
select0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = false;
enableChk2 = false;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
comboBox.setEnabled(false);
comboBox_1.setEnabled(false);
}
});
select0.setBounds(166, 169, 89, 23);
panel.add(select0);
comboBox = new JComboBox();
comboBox.setEnabled(enableChk1);
comboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox.setBounds(52, 100, 61, 20);
panel_1.add(comboBox);
comboBox_1 = new JComboBox();
comboBox_1.setEnabled(enableChk2);
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox_1.setBounds(265, 100, 79, 20);
panel_1.add(comboBox_1);
JButton back = new JButton("go back");
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.setVisible(true);
panel_1.setVisible(false);
}
});
back.setBounds(10, 227, 89, 23);
panel_1.add(back);
}
}
replace your code with this one. Its working Fine. Hope you are expecting this thing.

Unresponsive JTextField

In my application I need to get a response between 1 and 9 from the user. I am using a JTextField to get the input. However when a button is pressed the user the JTextField becomes unresponsive. Here is a stripped down example of the problem:
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
public class InputTest {
private JTextField inputBox;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new InputTest();
}
});
} // end main()
public InputTest() { // constructor
JFrame f = new JFrame("Input Test");
f.setBounds(100, 100, 450, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(null);
JLabel label = new JLabel("Enter an integer:");
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
label.setBounds(109, 120, 109, 30);
f.add(label);
inputBox = new JTextField();
inputBox.setBounds(259, 120, 30, 30);
f.add(inputBox);
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Pressed");
}
});
button.setMnemonic('B');
button.setBounds(166, 198, 78, 23);
f.add(button);
f.setVisible(true);
inputBox.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (c < '!' || e.getModifiers() > 0)
return;
if (c < '1' || c > '9') {
JOptionPane.showMessageDialog(null, c
+ " is not an integer");
// inputBox.setText("error");
System.out.println("You typed a non-integer");
} else
System.out.println("You typed " + c);
inputBox.setText(null);
}
});
} // end constructor
} // end class
You should almost never use a KeyListener with a Swing JTextComponent such as a JTextField, for example what happens when the user tries to copy and paste in their input? Instead consider using either a JFormattedTextField, or a JTextField with a DocumentFilter, or my choice -- a JSpinner.
import java.awt.event.ActionEvent;
import javax.swing.*;
public class InputTest2 extends JPanel {
private JSpinner spinner = new JSpinner(new SpinnerNumberModel(1, 1, 9, 1));
private JButton getSelectionButton = new JButton(new GetSelectionAction("Get Selection"));
public InputTest2() {
add(spinner);
add(getSelectionButton);
}
private static void createAndShowGui() {
InputTest2 mainPanel = new InputTest2();
JFrame frame = new JFrame("InputTest2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
private class GetSelectionAction extends AbstractAction {
public GetSelectionAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent evt) {
int value = ((Integer)spinner.getValue()).intValue();
System.out.println("You've selected " + value);
}
}
}

Categories

Resources