JButtons not displaying until mouse hover - java

I'm creating a gui that has 2 panels. When the gui is first loaded only one panel is visible and when a button is pressed the new panel is displayed. The problem is that on the 2nd panel when it loads the buttons are invisible and only display when the mouse hovers over them. On top of that when you move the screen they become invisible again and need to be hovered over to be displayed again.
I really don't know what to try as I have looked at methods of having multiple panels and this seems the best way to do it and aswell as this the buttons are implmented the same way I have implemented them for the 1st panel and they render correctly.
Full Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui {
private JFrame frame;
private JPanel panel1;
private JPanel panel2;
private JButton btnShip1, btnShip2, btnShip3, btnTutorial, btnLeftControl, btnHull, btnTargeting, btnRadar, btnWarning, btnRightControl;
private JTextField txtCharacterName, txtShipName;
private JLabel welcome, background;
public static void main(String[] args) {
new Gui();
}
public Gui(){
createWindow();
addButtons();
addFields();
addWelcome();
frame.add(panel1);
frame.setVisible(true);
addBackground();
addShipControls();
}
public void createWindow(){
frame = new JFrame();
frame.setTitle("Space Battle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(642, 518);
panel1 = new JPanel();
panel1.setLayout(null);
panel1.setBackground(Color.decode("#242627"));
panel2 = new JPanel();
panel2.setLayout(null);
panel2.setBackground(Color.decode("#242627"));
}
public void addButtons(){
btnShip1 = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/cruiserSelectBtn.jpg");
btnShip1.setIcon(img);
}
catch (Exception e) {}
try
{
ImageIcon img = new ImageIcon ("resources/button_1_hover.gif");
btnShip1.setRolloverIcon(img);
}
catch (Exception e) {}
btnShip1.setBounds(246,0,380,160);
btnShip1.setMargin(new Insets(0, 0, 0, 0));
btnShip1.addActionListener(new cruiserSelectHandler());
btnShip1.setBorder(null);
panel1.add (btnShip1);
btnShip2 = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/fighterSelectBtn.jpg");
btnShip2.setIcon(img);
}
catch (Exception e) {}
try
{
ImageIcon img = new ImageIcon ("resources/button_2_hover.gif");
btnShip2.setRolloverIcon(img);
}
catch (Exception e) {}
btnShip2.setBounds(246,160,380,160);
btnShip2.setMargin(new Insets(0, 0, 0, 0));
btnShip2.addActionListener(new fighterSelectHandler());
btnShip2.setBorder(null);
panel1.add (btnShip2);
btnShip3 = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/battleSelectBtn.jpg");
btnShip3.setIcon(img);
}
catch (Exception e) {}
try
{
ImageIcon img = new ImageIcon ("resources/button_3_hover.gif");
btnShip3.setRolloverIcon(img);
}
catch (Exception e) {}
btnShip3.setBounds(246,320,380,160);
btnShip3.setMargin(new Insets(0, 0, 0, 0));
btnShip3.addActionListener(new battleSelectHandler());
btnShip3.setBorder(null);
panel1.add (btnShip3);
btnTutorial = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/tutorialBtn.jpg");
btnTutorial.setIcon(img);
}
catch (Exception e) {}
btnTutorial.setBounds(5,426,234,49);
btnTutorial.setMargin(new Insets(0, 0, 0, 0));
panel1.add (btnTutorial);
}
public void addFields(){
txtCharacterName = new JTextField("Insert Character Name");
txtCharacterName.setBounds(12,260,220,35);
panel1.add(txtCharacterName);
txtShipName = new JTextField("Insert Ship Name");
txtShipName.setBounds(12,315,220,35);
panel1.add(txtShipName);
}
public void addWelcome(){
welcome = new JLabel ();
try
{
ImageIcon img = new ImageIcon ("resources/welcome.jpg");
welcome.setIcon(img);
}
catch (Exception e) {}
welcome.setBounds(0,0,247,229);
panel1.add(welcome);
}
//Class used to change panels
class cruiserSelectHandler implements ActionListener {
public void actionPerformed(ActionEvent even) {
frame.add(panel2);
panel1.setVisible(false);
}
}
class fighterSelectHandler implements ActionListener {
public void actionPerformed(ActionEvent even) {
frame.add(panel2);
panel1.setVisible(false);
}
}
class battleSelectHandler implements ActionListener {
public void actionPerformed(ActionEvent even) {
frame.add(panel2);
panel1.setVisible(false);
}
}
public void addBackground(){
//Is the background interfering?
background = new JLabel ();
try
{
ImageIcon img = new ImageIcon ("resources/background.jpg");
background.setIcon(img);
}
catch (Exception e) {}
background.setBounds(0,0,640,480);
panel2.add(background);
}
//Class used to add controls/buttons
public void addShipControls(){
btnLeftControl = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/left_controls.png");
btnLeftControl.setIcon(img);
}
catch (Exception e) {}
btnLeftControl.setBounds(-8,319,131,160);
btnLeftControl.setMargin(new Insets(0, 0, 0, 0));
btnLeftControl.setBorder(null);
panel2.add (btnLeftControl);
btnHull = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/hull_controls.png");
btnHull.setIcon(img);
}
catch (Exception e) {}
btnHull.setBounds(123,319,91,160);
btnHull.setMargin(new Insets(0, 0, 0, 0));
btnHull.setBorder(null);
panel2.add (btnHull);
btnTargeting = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/targeting_controls.png");
btnTargeting.setIcon(img);
}
catch (Exception e) {}
btnTargeting.setBounds(214,319,202,160);
btnTargeting.setMargin(new Insets(0, 0, 0, 0));
btnTargeting.setBorder(null);
panel2.add (btnTargeting);
btnWarning = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/warning_controls.png");
btnWarning.setIcon(img);
}
catch (Exception e) {}
btnWarning.setBounds(416,411,86,68);
btnWarning.setMargin(new Insets(0, 0, 0, 0));
btnWarning.setBorder(null);
panel2.add (btnWarning);
btnRadar = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/radar_idea.gif");
btnRadar.setIcon(img);
}
catch (Exception e) {}
btnRadar.setBounds(416,319,86,92);
btnRadar.setMargin(new Insets(0, 0, 0, 0));
btnRadar.setBorder(null);
panel2.add (btnRadar);
btnRightControl = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/right_controls.png");
btnRightControl.setIcon(img);
}
catch (Exception e) {}
btnRightControl.setBounds(502,319,131,160);
btnRightControl.setMargin(new Insets(0, 0, 0, 0));
btnRightControl.setBorder(null);
panel2.add (btnRightControl);
}
}

when a button is pressed the new panel is displayed.
The problem is:
you are using a null layout
you are add two different panels to the frame.
By default Swing paints components in the reverse order that they were added.
So when you add panel1, it is the only panel of the frame so it is painted.
Then you click a button and add panel2. So Swing paints panel2 and then repaints panel1 on top, so panel2 is hidden. When you mouse over the button it appears because buttons listen for mouseEntered events and the button gets repainted.
When you resize the screen panel2 is painted and then panel1 is painted so you have the problem again.
The solution is to use a proper layout manager. In your case you should be using a Card Layout. The Card Layout will swap panels making sure only one panel is ever visible at a time. Read the Swing tutorial on Using Card Layout. Then get rid of all the null layouts and setBounds() methods.

Related

How do you display an image on a panel in Java? [Beginner]

I need to put a menu in a game, so I've created a frame called menuFrame and a panel called menuPanel. I've been able to get a button and a label with text to appear on this panel, but I can't get an image to display.
Here is the bulk of my code:
try {
JPanel menuPanel = new JPanel();
BufferedImage img = ImageIO.read(this.getClass().getResource("background2.png"));
JLabel menuLabel = new JLabel(new ImageIcon(img));
menuLabel.setSize(800, 540);
menuLabel.setLocation(0, 0);
menuLabel.setVisible(true);
menuPanel.add(menuLabel);
this.add(menuPanel);
menuPanel.grabFocus();
menuPanel.requestFocusInWindow();
} catch (IOException e) {
e.printStackTrace();
}
I've been messing with it for a very long time, and the image simply wont appear. I've tried using just ImageIcon and no BufferedImage and that didn't work. I put the image in the same package as the class.
You could do something like this:
ImageIcon imgIcon = new ImageIcon("background2.png");
JLabel menuLabel = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(imgIcon);
try {
JPanel menuPanel = new JPanel();
BufferedImage img = ImageIO.read(this.getClass().getResource("background2.png"));
JLabel menuLabel = new JLabel(new ImageIcon(img));
menuLabel.setSize(800, 540);
menuLabel.setLocation(0, 0);
menuLabel.setVisible(true);
menuPanel.add(menuLabel);
this.add(menuPanel); //This might not work, try the name of the JFrame instance
menuPanel.grabFocus();
menuPanel.requestFocusInWindow();
this.revalidate() //Use the name of the JFrame if this is not a JFrame or if this.add(menuPanel); doesnt work
} catch (IOException e) {
e.printStackTrace();
}

Java layout when using JScrollPane

This is my code
private static KeyEvent e;
private static String text1 = null;
private static String text = null;
public fysikdel() {
super("Fysikformler");
setSize(700, 502);
setDefaultCloseOperation(EXIT_ON_CLOSE);
init();
setResizable(true);
setVisible(true);
}
public void init() {
JPanel main = new JPanel();
JPanel p = new JPanel();
CardLayout c1 = new CardLayout();
JScrollPane scrollpane = new JScrollPane(p);
JPanel Mekanik = new JPanel();
p.setSize(700, 502);
Mekanik.setLayout(new FlowLayout());
//637*237
ImageIcon likformigrorelsei = new ImageIcon();
JLabel likformigrorelsel = new JLabel();
ImageIcon lagesenergii = new ImageIcon();
JLabel lagesenergil = new JLabel();
ImageIcon a = new ImageIcon();
JLabel aa = new JLabel();
ImageIcon b = new ImageIcon();
JLabel bb = new JLabel();
try {
likformigrorelsei = new ImageIcon(new URL("http://i.imgur.com/TZFkXYa.jpg"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
likformigrorelsel.setIcon(likformigrorelsei);
try {
lagesenergii = new ImageIcon(new URL("http://i.imgur.com/TZFkXYa.jpg"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
lagesenergil.setIcon(lagesenergii);
try {
a = new ImageIcon(new URL("http://i.imgur.com/TZFkXYa.jpg"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
aa.setIcon(a);
try {
b = new ImageIcon(new URL("http://i.imgur.com/TZFkXYa.jpg"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
bb.setIcon(b);
Mekanik.add(likformigrorelsel);
Mekanik.add(lagesenergil);
Mekanik.add(aa);
Mekanik.add(bb);
JPanel Tryck = new JPanel();
main.setLayout(new GridLayout(1,1));
p.setLayout(c1);
this.add(main);
main.add(scrollpane);
p.add(Mekanik, "1");
p.add(Tryck, "2");
c1.show(p, "1");
When I add more pictures I want them to fill up from left to right untill one row is filled, then fill the next row. At the moment it just continue to fill the first row.
If I add
scrollpane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
it just removes the horizontal scroll bar but the pictures are still ending up on one row.
I dont know what is wrong. Thanks for any help!
So you put all your images in the Mekanik panel, which uses a FlowLayout. As the java tutorial states,
The FlowLayout class puts components in a row, sized at their preferred size
which is obviously not what you want. So you'll have to change the layout used by your panel.
To my mind, the GridLayout would be a better fit for your problem.

JPanels content doesn't reshow

I had spent two days in solving this problem but I have not found any solution.
I will put some easy code.
There is JFrame with some menu Bar, JPanels, but we focus on 2 options:
"Create Server"
"Close connection"
When I create server, on JPanel I draw checkerboard, and when I close connection, JPanel is clean, but the problem begins when I want to create server one more time, JPanel shows nothing.
I checked the input JPanel, and I put required JPanel before recreate server - nothing
I thought maybe it's gameControl, but I use it in other cases and it works also.
If anybody wants to try:
Here is entire project: http://bycniebytem.cba.pl/checkers.rar
Problem is inside the Checkers.java class,
But I'm waiting for your advices! Thanks!
hostServer.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
hostServer.setEnabled(false);
closeConnection.setEnabled(true);
server = new Server();
try
{
JPanel networkPanel = new JPanel();
player1 = new Player(1,boardSize, fieldSize);
player1.gameControl.setBounds(10, 10, boardSize*fieldSize + 10, boardSize*fieldSize + 10);
player1.gameControl.setSize(boardSize*fieldSize, boardSize*fieldSize);
player1.gameControl.addMouseListener(player1.gameControl);
player1.gameControl.addMouseMotionListener(player1.gameControl);
player1.gameControl.setFocusable(true);
player1.gameControl.setPreferredSize(new Dimension(boardSize*fieldSize,boardSize*fieldSize));
player1.connectWithServer(server.serverSocket.getInetAddress().getHostAddress());
JPanel votePanel = new JPanel();
JRadioButton whiteRadioButton = new JRadioButton("White");
JRadioButton blackRadioButton = new JRadioButton("Black");
blackRadioButton.setBounds(1, 1, 100, 30);
whiteRadioButton.setBounds(1, blackRadioButton.getHeight() + 5, 100, 30);
JButton bReady = new JButton("Ready");
bReady.setBounds(1, whiteRadioButton.getHeight() + 5, 100, 30);
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(whiteRadioButton);
radioGroup.add(blackRadioButton);
votePanel.add(blackRadioButton);
votePanel.add(whiteRadioButton);
votePanel.add(bReady);
votePanel.setBounds(player1.gameControl.getWidth() + 10, 10, blackRadioButton.getWidth(), blackRadioButton.getHeight() * 3);
votePanel.setPreferredSize(new Dimension(blackRadioButton.getWidth(), player1.gameControl.getHeight()));
setSize(boardSize * fieldSize + votePanel.getWidth() + 50, getJMenuBar().getHeight() + boardSize * fieldSize + 20);
networkPanel.add(player1.gameControl);
networkPanel.add(votePanel);
add(networkPanel);
setContentPane(networkPanel);
}
catch(IOException ex)
{
}
}
});
And close connection
closeConnection.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try
{
if(server != null)
{
if(server.getPlayerBlackSocket() != null)
{
server.sendMessage(server.getPlayerBlackSocket(), "closeConnection");
server.getPlayerBlackSocket().close();
}
if(server.getPlayerWhiteSocket() != null)
{
server.sendMessage(server.getPlayerWhiteSocket(), "closeConnection");
server.getPlayerWhiteSocket().close();
}
if(server.getServerSocket() != null)
{
server.getServerSocket().close();
}
}
}
catch (IOException ex)
{
}
player1.isOpenedConnection = false;
JPanel pane = (JPanel) getContentPane();
pane.removeAll();
remove(pane);
JPanel Pan = new JPanel();
JLabel label = new JLabel("label"); // just to test if jpanel can show and it shows
label.setBounds(10,10,100,30);
Pan.add(label);
setContentPane(Pan);
revalidate();
repaint();
closeConnection.setEnabled(false);
hostServer.setEnabled(true);
}
});

Jpanels inside JLayeredPanel

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);
}*/
}
}

Create new instance of JLabel each time it is clicked

I have a JPanel with a JLabel in it, is it possible to have a mouse click on JLabel, following by another mouse click on any location on the JPanel to create an instance of the JLabel. Basically, I can click the JLabel and create new instances of it anywhere on the JPanel.
Here is a simple example of what you are looking for. What you need is deepCopy of the clicked JLabel and then retrieve it back and draw it to the JPanel.
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.awt.*;
import javax.swing.border.*;
class CopyLabel extends JFrame
{
JPanel panel ;
JPanel centerPanel;
int clickCount = 0;
ByteArrayOutputStream baos;
ByteArrayInputStream bins;
public void createAndShowGUI()
{
setTitle("Copy JLabel");
JLabel label1 = new JLabel("JLabel1");
JLabel label2 = new JLabel("JLabel2");
panel = new JPanel();
label1.setForeground(Color.blue);
label2.setForeground(Color.red);
panel.add(label1);
panel.add(label2);
class MyMouseAdapter extends MouseAdapter
{
#Override
public void mouseClicked(MouseEvent evt)
{
clickCount = 1;
try
{
deepCopy((JLabel)evt.getSource());
}
catch (Exception ex){}
}
}
label1.addMouseListener(new MyMouseAdapter());
label2.addMouseListener(new MyMouseAdapter());
panel.setBorder(BorderFactory.createTitledBorder("Controllers"));
getContentPane().add(panel,BorderLayout.SOUTH);
centerPanel = new JPanel();
centerPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(),"Drawing Pad",TitledBorder.CENTER,TitledBorder.TOP));
centerPanel.setLayout(null);
centerPanel.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent evt)
{
if (clickCount == 1)
{
try
{
pasteLabel(evt.getX(),evt.getY());
}
catch (Exception ex){}
}
}
});
getContentPane().add(centerPanel);
setSize(300,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void deepCopy(JLabel label)throws Exception
{
baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(label);
oos.close();
}
public void pasteLabel(int x, int y)throws Exception
{
if (clickCount == 1)
{
bins = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream oins = new ObjectInputStream(bins);
JLabel obj = (JLabel)oins.readObject();
centerPanel.add(obj);
obj.setBounds(x,y,obj.getWidth(),obj.getHeight());
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
CopyLabel cl = new CopyLabel();
cl.createAndShowGUI();
}
});
}
}
You can attach mouse listener to your JLabel like this
final JLabel jlabel = new JLabel("Test");
jlabel.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Hello : "+ e);
Point location = MouseInfo.getPointerInfo().getLocation();
targetPanel.add(cloneLabelAt(jlabel, location));
}
});
private JLabel cloneLabelAt(JLabel label, Point location)
{
JLabel cloned = new JLabel(label.getText());
cloned.setLocation(location);
return cloned;
}
Inside your mouse click handler you can create another JLabel and add it to your target panel

Categories

Resources