I'm having problems getting my JPanel to display properly. I want to use different extended JPanels to display what I want the user to do with this program (which is ultimately to display photographs). Below is the code for the only two classes that exist at this point. Unfortunately, I'm having problems just getting this to work right out of the gate with the first panel which was to present the user with the ability to select different graphic images.
What's happening is, I can't get my JPanel to display until I click the "Open" menu item in the File menu. Once that JOptionPane shows, so does my JPanel (NewAlbum).
class PhotoGallery {
static JPanel transientPanel = null;
static final JFrame mainFrame = new JFrame("Photo Gallery");
public static void main(String[] args) {
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem open = new JMenuItem("Open");
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(mainFrame, "Hello World");
}
});
fileMenu.add(open);
JMenuItem newAlbum = new JMenuItem("New Album");
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AssignToTransientPanel((JPanel) new NewAlbum());
Container content = mainFrame.getContentPane();
content.removeAll();
content.add(transientPanel);
content.validate();
content.repaint();
}
});
fileMenu.add(newAlbum);
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
fileMenu.add(exit);
JMenuBar pgMenu = new JMenuBar();
pgMenu.add(fileMenu);
mainFrame.setJMenuBar(pgMenu);
mainFrame.setSize(640, 480);
mainFrame.setLocation(20, 45);
mainFrame.validate();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
public static void AssignToTransientPanel(JPanel jp) {
if(transientPanel != null)
mainFrame.remove(transientPanel);
transientPanel = jp;
}
}
}
class NewAlbum extends JPanel {
JButton selectImages = new JButton("Select Images");
JFileChooser jfc;
File[] selectedFiles;
public NewAlbum() {
selectImages.setLocation(25, 25);
add(selectImages);
selectImages.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent ae) {
jfc = new JFileChooser();
jfc.setMultiSelectionEnabled(true);
jfc.showOpenDialog(getParent());
selectedFiles = jfc.getSelectedFiles();
}
});
this.validate();
}
public int getHeight() {
return getParent().getSize().height - 20;
}
public int getWidth() {
return getParent().getSize().width - 20;
}
public Dimension getPreferredSize() {
return new Dimension(this.getWidth(), this.getHeight());
}
}
You have not added any components to the mainFrame's content pane in the main method. The only time a panel gets added is in this ActionListener:
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AssignToTransientPanel((JPanel) new NewAlbum());
Container content = mainFrame.getContentPane();
content.removeAll();
content.add(transientPanel);
content.validate();
content.repaint();
}
});
This is only getting called when "Open" is clicked as you have, I assume accidentally, added the ActionListener to the open JMenuItem rather than the newAlbum JMenuItem. To add content on startup you need to add something like this before the mainFrame.setVisible(true) line:
mainFrame.add(new NewAlbum());
BTW, the convention is for all methods in Java source code to start with a lower case letter. assignToTransientPanel would be a better name for your method.
Related
I have started working with JFrames and am creating a simple programme with 3 panels that are different colours and I was just wondering what would be the best way to switch between panels for my programme. The panels are to be changed when a JMenuItem with the colours name is selected. I was looking at cards and was wondering if they would be a good solution and if it would be possible to implement them into my programme? Any other suggestions would be greatly appreciated & apologies if I have done anything wrong ive only started on stack overflow and am quite a newcomer to Java :)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Colour extends JFrame
{
CardLayout card;
JPanel childPanel = new JPanel(), redPanel, bluePanel, greenPanel;
Container c;
public Colour(){
// Get Container
c=getContentPane();
//Create Menu and items
childPanel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu customer = new JMenu("Colour");
customer.setMnemonic(KeyEvent.VK_U);
JMenuItem blue = new JMenuItem("Blue");
JMenuItem red = new JMenuItem("Red");
JMenuItem green = new JMenuItem("Green");
customer.add(blue);
customer.add(red);
customer.add(green);
menuBar.add(customer);
this.setJMenuBar(menuBar);
//Adding panel to container
c.add(childPanel);
childPanel.setBackground(Color.PINK);
//Action Listeners for switching panels
blue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
} );
red.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
} );
green.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
} );}
//Creating my different panels and adding them to childPanel
public void redC() {
redPanel = new JPanel();
redPanel.setBackground(Color.RED);
childPanel.add(redPanel, "Red");
}
public void blueC() {
bluePanel = new JPanel();
bluePanel.setBackground(Color.BLUE);
childPanel.add(bluePanel, "Blue");
}
public void greenC() {
greenPanel = new JPanel();
greenPanel.setBackground(Color.GREEN);
childPanel.add(greenPanel, "Green");
}
public static void main(String[] args) {
Colour cl=new Colour();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
You are almost done with you code.
Here is the working code.
You need to revalidate the childPanel after adding/removing a panel so that it will be repainted:
//Action Listeners for switching panels
blue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (childPanel.getComponentCount() >0)
childPanel.remove(0);
blueC();
childPanel.revalidate();
}
});
red.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (childPanel.getComponentCount() > 0)
childPanel.removeAll();
redC();
childPanel.revalidate();
}
});
green.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (childPanel.getComponentCount() > 0)
childPanel.remove(0);
greenC();
childPanel.revalidate();
}
});
i have the following code, where i try to make some jLabels/jComboBox visible/invisible and move the location of those that are visible on jRadioButton click.
the issue is that the location is updated only on second click.
private void SingleButtonActionPerformed(java.awt.event.ActionEvent evt) {
this.serverLabel.setVisible(true);
this.serverList.setVisible(true);
this.serverLabel.setLocation(this.hostGroupLabel.getLocation().x, this.cpuCountSpinner.getLocation().y);
this.serverList.setLocation(this.cpuCountSpinner.getLocation().x, this.cpuCountSpinner.getLocation().y);
this.jXDatePickerStartDate.setLocation(153, jXDatePickerStartDate.getLocation().y);
this.requestedRamLabel.setVisible(false);
this.ramText.setVisible(false);
this.cpuLabel.setVisible(false);
this.cpuCountSpinner.setVisible(false);
}
I dont know why it is not working for you, mayby you are modifying somewhere else your GUI, or event is not fired at all. Here is working example. You should pase the code where you actually append the listener to the button. You did that right? It should be something like:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
singleButtonActionPerformed(e)
}
});
or Java8 variant using Lambdas
button.addActionListener(this::singleButtonActionPerformed)
but using this depends on context. It should be the object hta holds given method.
Here is working example with button and radio button (as suggested)
public class SettingLocation {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(400, 400);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
f.setContentPane(p);
p.setLayout(new FlowLayout());
JButton b = new JButton("Click me");
b.setBounds(150, 150,100,100);
p.add(b);
JRadioButton rb=new JRadioButton("Exmaple radio");
p.add(rb);
rb.addActionListener(new ActionListener() {
Random r = new Random();
#Override
public void actionPerformed(ActionEvent e) {
rb.setLocation(r.nextInt(300), r.nextInt(300));
}
});
b.addActionListener(new ActionListener() {
Random r = new Random();
#Override
public void actionPerformed(ActionEvent e) {
b.setLocation(r.nextInt(300), r.nextInt(300));
}
});
f.setVisible(true);
}
}
I'm writing a Chat program. I designed a mock-up gui with smileys where when the user clicks on a smiley(jbutton) it prints it onto a textpane. I managed to add an advanced feature where when a user types in ":)" and sends it, it inserts the smiley instead of the string - using the insertIcon() method. The problem I have is that it only prints the smiley once rather than multiple times. So if I type "Hi :) My name is Jack :)" it only inserts the icon ONCE. Any suggestions?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SmileyTesterGUI extends JFrame {
JPanel main = new JPanel();
JPanel south = new JPanel();
JPanel messageCenter = new JPanel();
JPanel smileysNorth = new JPanel();
JTextField text;
JTextPane tPane;
Icon happy;
Icon smile;
Icon tongue;
Icon veryHappy;
Icon wink;
Icon laugh;
Icon sad;
Icon verySad;
Icon cry;
public SmileyTesterGUI() {
super("Smileys");
add(main);
main.setLayout(new BorderLayout());
main.add(south, BorderLayout.SOUTH);
south.setLayout(new BorderLayout());
south.add(messageCenter, BorderLayout.CENTER);
south.add(smileysNorth, BorderLayout.NORTH);
// textpane panel
tPane = new JTextPane();
JScrollPane sPane = new JScrollPane(tPane);
main.add(sPane);
tPane.setEditable(false);
// smileysPanel
smileysNorth.setLayout(new GridLayout(1, 0));
JButton smiley1 = new JButton();
JButton smiley2 = new JButton();
JButton smiley3 = new JButton();
JButton smiley4 = new JButton();
JButton smiley5 = new JButton();
JButton smiley6 = new JButton();
JButton smiley7 = new JButton();
JButton smiley8 = new JButton();
JButton smiley9 = new JButton();
smileysNorth.add(smiley1);
smileysNorth.add(smiley2);
smileysNorth.add(smiley3);
smileysNorth.add(smiley4);
smileysNorth.add(smiley5);
smileysNorth.add(smiley6);
smileysNorth.add(smiley7);
smileysNorth.add(smiley8);
smileysNorth.add(smiley9);
// set smileys(icon) to each button - pathed from personal directory
happy = new ImageIcon(getClass().getResource("smileys/Smile1.png"));
smiley1.setIcon(happy);
smile = new ImageIcon(getClass().getResource("smileys/Smile2.png"));
smiley2.setIcon(smile);
tongue = new ImageIcon(getClass().getResource("smileys/Smile3.png"));
smiley3.setIcon(tongue);
veryHappy = new ImageIcon(getClass().getResource("smileys/Smile4.png"));
smiley4.setIcon(veryHappy);
wink = new ImageIcon(getClass().getResource("smileys/Smile5.png"));
smiley5.setIcon(wink);
laugh = new ImageIcon(getClass().getResource("smileys/Smile6.png"));
smiley6.setIcon(laugh);
sad = new ImageIcon(getClass().getResource("smileys/Smile7.png"));
smiley7.setIcon(sad);
verySad = new ImageIcon(getClass().getResource("smileys/Smile8.png"));
smiley8.setIcon(verySad);
cry = new ImageIcon(getClass().getResource("smileys/Smile9.png"));
smiley9.setIcon(cry);
// smileys print on the textpane
smiley1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile1.png")));
}
});
smiley2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile2.png")));
}
});
smiley3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile3.png")));
}
});
smiley4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile4.png")));
}
});
smiley5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile5.png")));
}
});
smiley6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile6.png")));
}
});
smiley7.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile7.png")));
}
});
smiley8.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile8.png")));
}
});
smiley9.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile9.png")));
}
});
// messagePanel
messageCenter.setLayout(new BorderLayout());
text = new JTextField();
JButton send = new JButton("Send");
messageCenter.add(text);
messageCenter.add(send, BorderLayout.EAST);
text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMessage();
}
});
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMessage();
}
});
setLocation(500, 0);
setSize(600, 250);
}
public void sendMessage() {
String a = text.getText();
// tPane.setText(a);
// tPane.getText();
if (a.equals(":D")) {
tPane.insertIcon(veryHappy);
} else if (a.equals(":)")) {
tPane.insertIcon(smile);
} else if (a.equals(":(")) {
tPane.insertIcon(sad);
} else if (a.equalsIgnoreCase(":P")) {
tPane.insertIcon(tongue);
} else if (a.equals(";)")) {
tPane.insertIcon(wink);
}
text.setText(null);
text.requestFocus();
}
public static void main(String[] args) {
new SmileyTesterGUI().setVisible(true);
}
}
insertIcon() method of JTextPane uses selection (caret position in simplest case). So in your case you always replace the icon just once.
Your sendMessage() doesn't check multiple occurences of ":)" in the message. Use while loop obtaining indexes of the ":)" and for each index make it selected and then use insertIcon()
I have a Swing application, And when i run VoiciOver Utility it announce Swing Application as Java.
For example:
import javax.swing.*;
import java.awt.event.*;
public class Menu extends JFrame{
public Menu()
{
super("Menu example");
JMenu file = new JMenu("File");
file.setMnemonic('F');
JMenuItem newItem = new JMenuItem("New");
newItem.setMnemonic('N');
file.add(newItem);
JMenuItem openItem = new JMenuItem("Open");
openItem.setMnemonic('O');
file.add(openItem);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
file.add(exitItem);
//adding action listener to menu items
newItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("New is pressed");
}
}
);
openItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Open is pressed");
}
}
);
exitItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Exit is pressed");
}
}
);
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
bar.add(file);
getContentPane();
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args)
{
Menu app = new Menu();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
If we try this example with voiceOver utility,it announces the application as "java Menu example window".
can some one help me in resolving this issue?
You can set the com.apple.mrj.application.apple.menu.about.name property to change the displayed name, as shown here.
Whenever I add a background (Image img) to my JFrame I am unable to see my menu bar .... Any help would be greatly appreciated ... I'm just learning JFrames and am probably overlooking something stupid.
class GameFrame extends JFrame {
private JLabel statusbar;
Image img = new ImageIcon("splash.png").getImage();
public GameFrame() {
initUI();
menuUI();
BackgroundLoader bg = new BackgroundLoader();
}
#Override
public void paint(Graphics g) {
try {
Image img = ImageIO.read(new File("splash.png"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
} catch (IOException e) {
e.printStackTrace();
}
}
public final void initUI() {
setTitle("Super RPG Hero: The Quest for Fame and Fortune");
setSize(800, 480);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//JLabel background = new JLabel(splash);
//background.setBounds(0, 0, splash.getIconWidth(), splash.getIconHeight());
//getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));
}
public final void menuUI() {
JMenuBar menubar = new JMenuBar();
//Creates file menu item
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
//Creates Object for New Game toolbar
JMenuItem newItem = new JMenuItem("New Game");
newItem.setMnemonic(KeyEvent.VK_C);
newItem.setToolTipText("New Game");
newItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String playerName = "Peter";
CharacterCreator characterOne = new CharacterCreator(playerName);
characterOne.statBuilder();
}
});
//Creates Object for Save Game toolbar
JMenuItem saveItem = new JMenuItem("Save");
saveItem.setMnemonic(KeyEvent.VK_C);
saveItem.setToolTipText("Save Game");
//Creates Object for Load Game toolbar
JMenuItem loadItem = new JMenuItem("Load");
loadItem.setMnemonic(KeyEvent.VK_C);
loadItem.setToolTipText("Load Game");
//Creates Object for Exit Game toolbar
//And creates method for the game to exit
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_C);
exitItem.setToolTipText("Exit Game");
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
//Adds created objects to GUI
file.add(newItem);
file.add(saveItem);
file.add(loadItem);
file.add(exitItem);
menubar.add(file);
setJMenuBar(menubar);
}
}
You should implement paintComponent() and not paint().
By overriding paint and not delegating up, you're not letting the JFrame paint what it needs to paint.
Also, look at this answer.