Hi does anyone know why my "button1" is not displaying? I can not seem to figure it out when I execute the program it all works and runs successfully but it does not display this button. Any help would be appreciated thanks.
private Container c;
private JPanel gridPanel;
private JComboBox combo;
final JLabel label = new JLabel();
private JButton button1 = new JButton("Clear");
private JButton button2 = new JButton("Exit");
/**
* Christopher Haddad - 559815X
*/
public Planets() {
c = getContentPane();
gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(5, 0, 0, 0));
label.setVisible(true);
combo = new JComboBox();
combo.setEditable(false);
combo.addItem("No Planet Selected");
combo.addItem("Mercury");
combo.addItem("Venus");
combo.addItem("Earth");
gridPanel.add(combo);
add(button1);
add(button2);
button1.addActionListener(this);
button2.addActionListener(this);
c.add(gridPanel, BorderLayout.NORTH);
setTitle("Planet Diameter");
setSize(700, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JComboBox comboBox = (JComboBox) event.getSource();
Object select = comboBox.getSelectedItem();
if(select.toString().equals("No Planet Selected"))
label.setText("");
else if(select.toString().equals("Mercury"))
label.setText("The planet Mercury is 3100kms in diameter");
else if(select.toString().equals("Venus"))
label.setText("The planet Venus is 7500kms in diameter");
else if (select.toString().equals("Earth"))
label.setText("The planet Earth is 8000kms in diameter");
}
});
getContentPane().add(combo);
getContentPane().add(label);
}
// event handling method, implementing the actionPerformed method of ActionListener
public void actionPerformed(ActionEvent e)
{
// set the button label to number of times it has been clicked
if(e.getSource() == button1) {
label.setText(" ");
}
else if(e.getSource() == button2) {
System.exit(0);
}
}
It is difficult to be sure, but I assume you are adding content directly to a top level container, like a JFrame
JFrame uses a BorderLayout as it's default layout manager, so using
add(button1);
add(button2);
Basially says, add button1 to the CENTER position then add button2 to the CENTER position. BorderLayout will only allow a single component to exist at a specific location.
Try adding the buttons to another panel first...
Related
I'm trying to add a button using an JOptionPane in another button, but after I clicked the original button just keeps disappearing.
I've tried adding the JPanel manually instead of using 'handPanelNPC.getHandPanel()' by iterating through the handPanel.buttons but it stil wont work. I've checked the ArrayList size and it is already inserted properly.
LayoutTesting.java
public class LayoutTesting extends JFrame{
HandPanel handPanelNPC = new HandPanel();
public LayoutTesting(HandPanel handPanel, int type){
Container pane = getContentPane();
if (type==1){
handPanelNPC = handPanel;
}
pane.setLayout(new BorderLayout());
pane.add(handPanelNPC.getHandPanel(), BorderLayout.NORTH);
validate();
repaint();
}
public LayoutTesting(){
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(handPanelNPC.getHandPanel(), BorderLayout.NORTH);
}
}
HandPanel.java
public class HandPanel implements ActionListener{
JFrame frame = null;
JPanel panel = new JPanel();
ArrayList<JButton> buttons = new ArrayList<JButton>();
public HandPanel(){
addNewButton();
panel.setLayout(new FlowLayout());
panel.add(buttons.get(0));
}
public JComponent getHandPanel(){
panel = new JPanel();
for(int i=0; i<buttons.size(); i++){
JButton button = buttons.get(i);
panel.add(button);
}
return panel;
}
public void addNewButton(){
JButton button = new JButton();
button.setPreferredSize(new Dimension(40,58));
button.addActionListener(this);
buttons.add(button);
}
public void actionPerformed(ActionEvent e) {
String[] options = {"Summon", "Set", "Add Card"};
int messageType = JOptionPane.QUESTION_MESSAGE;
int code = JOptionPane.showOptionDialog(
frame,
"What would you like to do?",
"Card Name",
0, messageType, null,
options, options[1]);
if (code==2){
addNewButton();
LayoutTesting frame = new LayoutTesting(this, 1);
}
}
}
Main.java
public class Main extends JFrame{
public static void main(String[] args){
LayoutTesting frame = new LayoutTesting();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
You have too many odd things happening in your code to give a simple answer.
Try debugging your own code by looking at this line in HandPanel.java:
LayoutTesting frame = new LayoutTesting(this, 1);
What does it really do? Now remove that line and the button will not disappear. Now try and work out what that line was doing, and why the button disappeared.
Also 'panel.add(buttons.get(0));' does nothing because there is never a button in the array when you make that call (You add the button afterwards in another method).
Here is a rough working demo that lets you add as many new cards as you want to the first frame, and each card has a button that will let you summon a new card.
public class LayoutTesting extends JFrame{
Container pane;
//Add card when button is pressed:
public void addCard(){
Container card = new JPanel();
card.setBackground(Color.red);
JButton newButton = addNewButton();
newButton.setBackground(Color.red);
card.add(newButton);
pane.add(card);
revalidate();
repaint();
}
//Setup window and add button:
public LayoutTesting(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
setLayout(new FlowLayout());
pane = new JPanel();
pane.setLayout(new GridBagLayout());
JButton firstButton = addNewButton();
firstButton.setBackground(Color.green);
add(pane);
add(firstButton);
}
//Create button and action listener:
public JButton addNewButton(){
JButton button = new JButton();
button.setPreferredSize(new Dimension(40, 58));
button.addActionListener(new java.awt.event.ActionListener(){
#Override
public void actionPerformed(java.awt.event.ActionEvent evt){
buttonAction(evt);
}
});
return button;
}
//Action fer each button:
public void buttonAction(ActionEvent e) {
String[] options = {"Summon", "Set", "Add Card"};
int messageType = JOptionPane.QUESTION_MESSAGE;
int code = JOptionPane.showOptionDialog(
this,
"What would you like to do?",
"Card Name",
0, messageType, null,
options, options[1]);
if (code==2){
addCard();
}
}
}
I'm in the early stages of making Battleships (just started a computer science degree) and had been using Eclipse on Windows. So far I've just created the grids and have added an actionlistener to the jbuttons so they change colour when clicked.
It works fine when I run it on my Windows PC, however when I try to run it on a mac, it just shows the basic grid and doesn't change colours or anything.
Anyone had a problem like this or can help? I can't figure out why it would work on one and not the other.
Thanks
Here is my code, if that helps (I know it's not elegant or anything right now)
public class BattleshipFrame {
public static void main(String[] args) {
//creating JFrame
JFrame frame = new JFrame("Battleship");
frame.setLayout(new GridLayout(1, 3));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//creating User Panel
JPanel userpanel = new JPanel();
userpanel.setLayout(new GridLayout(10, 10));
userpanel.setSize(400, 400);
//creating JButton array
JButton[] button = new JButton[100];
//putting JButtons in User Panel
for (int i = 0; i < 100; i++) {
button[i] = new JButton();
button[i].setBackground(Color.BLUE);
userpanel.add(button[i]);
//changing colour of buttons when clicked
button[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
Object source = ev.getSource();
if (source instanceof Component) {
((Component) source).setBackground(Color.GREEN);
}
}
});
}
//creating computer panel
JPanel comppanel = new JPanel();
comppanel.setLayout(new GridLayout(10, 10));
comppanel.setSize(400, 400);
//putting JButtons in User Panel
for (int i = 0; i < 100; i++) {
button[i] = new JButton();
button[i].setBackground(Color.BLUE);
comppanel.add(button[i]);
//changing colour of buttons when clicked
button[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
Object source = ev.getSource();
if (source instanceof Component) {
((Component) source).setBackground(Color.GREEN);
}
}
});
}
//creating menu panel
JPanel menupanel = new JPanel();
//creating buttons for menu
JButton save = new JButton("Save");
JButton load = new JButton("Load");
save.setPreferredSize(new Dimension(100, 100));
load.setPreferredSize(new Dimension(100, 100));
//adding buttons to menu panel
menupanel.add(save);
menupanel.add(load);
//adding panels into frame
frame.add(userpanel, BorderLayout.WEST);
frame.add(menupanel, BorderLayout.CENTER);
frame.add(comppanel, BorderLayout.EAST);
frame.setVisible(true);
frame.setSize(2000, 1000);
}
}
As I say, it works perfectly on my Windows Eclipse but not on Mac
I'm working on a Java assignment. I have many classes linked together and one of the constructors is the following:
public class RemovePatientForm extends JFrame implements ActionListener {
JPanel northPanel = new JPanel();
JPanel southPanel = new JPanel();
JPanel midPanel = new JPanel();
JLabel removeLabel = new JLabel("Please type in the ID of the patient to be removed");
JLabel idLabel= new JLabel("ID");
JTextField idText=new JTextField();
JButton submit = new JButton("Submit");
JButton reset = new JButton("Clear");
boolean externalForm = false;
public RemovePatientForm(){
setTitle("Removing a patient");
setLayout(new BorderLayout());
setSize(400,200);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
add("North", northPanel);
add("South", southPanel);
northPanel.add(removeLabel);
southPanel.add(submit);
southPanel.add(reset);
add(idLabel);
add(idText);
submit.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==submit){
if(!(idText.getText().equals(""))){
int selectedvalue = JOptionPane.showConfirmDialog(null, "Do you want to proceed with the deletion?", "do you want to proceed with the deletion?", JOptionPane.YES_NO_OPTION);
if(selectedvalue==JOptionPane.YES_OPTION){
int id=Integer.parseInt(idText.getText());
if(searchForId(id)){
removeToDatabase();
dispose();
}
else{
JOptionPane.showMessageDialog(null,"This ID is not available!","Warning",JOptionPane.ERROR_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(null, "Nothing is affected!");
}
}
else{
JOptionPane.showMessageDialog(null,"You have to fill the ID number!","Warning",JOptionPane.ERROR_MESSAGE);
}
}
if(arg0.getSource()==reset && externalForm==false){
idText.setText("");
}
}
The problem in here is that when I press the submit button, everything is okay and working as written within the code.
But, if I press the reset button, nothing is happening.
What do you think the solution is? is this code enough to determine the problem?
You didn't add an action listener for the reset button.. i think you forgot it. Try to add it and it should work.
Add this code within your constructor:
reset.addActionListener(this);
I am trying to get a JLabel to appear when a JButton is clicked. I have added an action listener and added the component to the layout. I am using the label1.setVisible(true) when the JButton is clicked in actionPerformed. I still can't get it work. Can some look at my code?
public class LearnAppMain extends JFrame implements ActionListener {
// Define variables
public JButton button1;
public JLabel label1;
public JTextField field1;
private Image image1;
private String apple = "apple.jpg";
public LearnAppMain() {
ImageIcon image1 = new ImageIcon(this.getClass().getResource(apple));
JLabel label1 = new JLabel(image1);
button1 = new JButton("A");
button1.addActionListener(this);
field1 = new JTextField(10);
// Create layout
setLayout(new FlowLayout());
// create Container
final Container cn = getContentPane();
cn.add(button1);
cn.add(field1);
cn.add(label1);
// setLayout(new FlowLayout());
setSize(250, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (e.getSource() == button1) {
label1.setVisible(true);
field1.setText("Apple");
}
}
}
I have my main method in another class file. The error I get leads me to the label1.setVisible(true);
Every question I've seen they say to do this, but I'm wondering if there is something else that needs to be added.
There were a couple of issues here:
Your label1 was hidden by doing JLabel label in the constructor. You basically declared another variable called label1 in your constructor that hid the one in the class itself.
Your label was visible on the startup - I used label.setVisible(false) for the test, but you might want otherwise
I also put the creation of Image aside as I did not have an image, so uncomment that and change as appropriate.
Here's a complete working version:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LearnAppMain extends JFrame implements ActionListener {
// Define variables
public JButton button1;
public JLabel label1;
public JTextField field1;
private Image image1;
private String apple = "apple.jpg";
public LearnAppMain() {
//ImageIcon image1 = new ImageIcon(this.getClass().getResource(apple));
//JLabel label1 = new JLabel(image1);
label1 = new JLabel("hello");
label1.setVisible(false);
button1 = new JButton("A");
button1.addActionListener(this);
field1 = new JTextField(10);
// Create layout
setLayout(new FlowLayout());
// create Container
final Container cn = getContentPane();
cn.add(button1);
cn.add(field1);
cn.add(label1);
// setLayout(new FlowLayout());
setSize(250, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (e.getSource() == button1) {
label1.setVisible(true);
field1.setText("Apple");
}
}
public static void main(String[] args) {
new LearnAppMain();
}
}
I'd suggest using separate (usually inner-class) ActionListener instances instead of overriding actionPerformed. See e.g. this for a similar example if you are interested:
http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/events/BeeperProject/src/events/Beeper.java
Also, if you are using this in a bigger application (i.e. not just experimenting or for prototyping), make sure all Swing code is run on EDT.
You typically use SwingUtilities.invokeLater for that purpose.
Hope this helps.
first you don't add the image first itself to JLabel.
just create the object and leave it like..
ImageIcon image1 = new ImageIcon(this.getClass().getResource(apple));
JLabel label1 = new JLabel("");
label1.setVisible(true);
then do the modification in the action performed
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1)
{
field1.seticon(image1);
field1.revalidate();
}
it will definitely works
clientDetail.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e){
d.getContentPane().removeAll();
g = new GridBagLayout();
gc = new GridBagConstraints();
d.setLayout(g);
JLabel message= new JLabel(" Message");
addComponent(message,5,1,1,2);
JTextArea Message = new JTextArea();
addComponent(Message,5,1,1,2);
d.setVisible(true);
d.setVisible(true);
d.pack();
}
private void addComponent(Component component, int i, int i0, int i1, int i2) {
gc.gridx=i;
gc.gridy=i0;
gc.gridheight=i1;
gc.gridwidth=i2;
g.setConstraints(component, gc);
add(component);
}
});
Recep.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
I got a little problem with a JOptionPane which I use to warn user if wrong input is found. It works correct first time. But when I close down the JFrame which calls for that JOptionPane, and open it again it will this time call for it twice. And it will stack for every close down I do.
I have tried to look for the problem without any luck. I can provide the code, but it is quite large though.
Third EDIT: I have found and solved the problem now.
Ok, I provided the code I use. I have cut it down so it only show the necessary one. I dont think it will compile, but this is how I use the addActionListener();
public class BorderLayoutDemo extends JFrame implements ActionListener {
private JButton button1 = new JButton("L?gg till kund");
private JButton button2 = new JButton("Ta bort kund");
private JButton button3 = new JButton("Visa kund");
private JButton button4 = new JButton("Lista alla kunder");
private JButton button5 = new JButton("Avsluta");
private JButton button6 = new JButton("Change");
private JTextArea TextWindow = new JTextArea("Hej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\n");
private JScrollPane scrollPane = new JScrollPane(TextWindow); //l?gger in TextWindow s? att det f?r en scroll-bar
private JPanel aPanel = new JPanel();
private JFrame aFrame = new JFrame();
private JTextField aTextfield1 = new JTextField();
private JTextField aTextfield2 = new JTextField();
private JButton aButton1 = new JButton("L?gg till kund");
private JButton aButton2 = new JButton("St?ng");
public BorderLayoutDemo() {
setTitle("Bankregister");
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
panel.setLayout(new GridLayout(6,1,55,5)); //row, cols, hgap, vgap
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
panel.add(button6);
JPanel panel2 = new JPanel();
panel2.add(panel);
add(panel2,BorderLayout.WEST);
add(scrollPane,BorderLayout.CENTER);
setJMenuBar(menu());
setSize(600,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void addCustomer(boolean status) {
if(status) {
aFrame.setTitle("L?gg till kund");
aFrame.setSize(200,300);
aFrame.setLayout(new GridLayout(3,1));
aPanel.setLayout(new GridLayout(2,1)); //rad, kolumn
aPanel.add(aTextfield1);
aPanel.add(aTextfield2);
aButton1.addActionListener(this);
aButton2.addActionListener(this);
System.out.println("Foo!!!!!!!!!!!!!");
aFrame.add(aPanel);
aFrame.add(aButton1);
aFrame.add(aButton2);
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.setLocationRelativeTo(null);
aFrame.setVisible(true);
}
else {
aFrame.setVisible(false);
}
}
public static void main(String[] args) {
new BorderLayoutDemo();
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1) {
setEnabled(false);
addCustomer(true);
}
//IFs f?r addCustomer();
else if(e.getSource() == aButton1) {
if((aTextfield1.getText().isEmpty() || aTextfield2.getText().isEmpty())) {
JOptionPane.showMessageDialog(null, "You miss to fill out the fields");
}
else {
JOptionPane.showMessageDialog(null, "Added");
Kund kund = new Kund(aTextfield1.getText(),aTextfield2.getText());
setEnabled(true);
register.add(kund);
}
}
else if(e.getSource() == aButton2) {
setEnabled(true);
addCustomer(false);
}
Sounds like you are adding the "validation listener" every time you open the JFrame. So check your "addListenerXXX" code to make sure it is only added/created once.
Which also leads to the question why are you using a JFrame for this? Typically an application has a single JFrame. Then, if you need a window to enter data you create a JDialog.
By passing null as the first parameter of that method you are creating a default JFrame that the JOptionPane uses as its parent component and not the JFrame you have created in your code. If you provide more detail in your question I'm sure someone here will provide you with a much more detailed answer.