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
Related
Im kind of new to programming in java but here im trying to figure out how to add the value of a button clicked in ActionEvent. I even changed the actionlistener to MouseListener etc but still not working. It only displays the current button clicked but i would like to add every button clicked into an arraylist.
Problem: I cant add the value of buttons clicked into an arraylist.
Example: if i click on the button named E then i want E to be added to arraylist, after that if i click on the button S then it should add S o the same arraylist.
but its not adding aything to the arraylist. it only displays the current button clicked
public class WordFinder extends JFrame implements ActionListener {
private JButton buttons[];
ArrayList<String> LettersClicked = new ArrayList<String>();
private JTextArea jta;
private JLabel jLabel;
public WordFinder(){
int numberOfLetters = 64;
buttons = new JButton[numberOfLetters];
JFrame frame = new JFrame("wordfinder");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.red);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel topPanel = new JPanel();
topPanel.setBorder(BorderFactory.createLineBorder(Color.GREEN));
topPanel.setPreferredSize(new Dimension(600, 600));
topPanel.setMaximumSize(new Dimension(600, 600));
topPanel.setBackground(Color.red);
JPanel bottomPanel = new JPanel();
bottomPanel.setBorder(BorderFactory.createLineBorder(Color.yellow));
bottomPanel.setPreferredSize(new Dimension(600, 300));
bottomPanel.setMaximumSize(new Dimension(600, 300));
bottomPanel.setBackground(Color.green);
Font f3 = new Font(Font.DIALOG, Font.BOLD, 35);
for (int i = 0;i<numberOfLetters;i++) {
char letter = alphabet();
buttons[i] = new JButton(String.valueOf(letter));
buttons[i].setFont(f3);
// buttons[i].setMinimumSize(new Dimension(40, 20));
buttons[i].setPreferredSize(new Dimension(65, 65));
buttons[i].setMargin(new Insets(0,0,0,0));
buttons[i].setBackground(Color.white);
buttons[i].setFocusPainted(false);
buttons[i].addActionListener(this);
topPanel.add(buttons[i]);
}
String buttValue = "";
jLabel = new JLabel(""+buttValue);
jLabel.setFont(f3);
bottomPanel.add(jLabel);
LettersClicked.add(jLabel.toString());
for (int z = 0; z<LettersClicked.size(); z++){
JLabel aa = new JLabel(""+LettersClicked.size());
bottomPanel.add(aa);
}
mainPanel.add(topPanel);
mainPanel.add(bottomPanel);
frame.getContentPane().add(mainPanel);
frame.setSize(1000,1000);
frame.setMinimumSize(new Dimension(1000, 1000));
frame.setVisible(true);
}
public char alphabet(){
Random rnd = new Random();
String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char letter = alphabets.charAt(rnd.nextInt(alphabets.length()));
return letter;
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
JButton button = (JButton) actionEvent.getSource();
jLabel.setText(button.getText());
LettersClicked.add(button.getText());
}
}
I think you are confused about the content of the JLabel displayed on the GUI and your ArrayList. The issue is actually in the former.
Your current implementation replaces the text of the JLabel instead of appending it for each pressed button.
So, in your actionPerformed() method, change this line
jLabel.setText(button.getText());
to
jLabel.setText(jLabel.getText() + button.getText());
I am learning Java and I have to develop an application using a GUI. I have the application working in command line already, but the GUI is driving me insane and costing me in lost hours of head banging and research which is leading nowhere. Can you please help me get the basics working so that i can develop further from there. I want to have a single frame application that can switch between frames on a button click. I created a frame and added three panels P1-P3. These are set as Card Layout (from what i read from forums). Then I added additional panels to these to which i have set colour and buttons.
'''
public class MyMainForm extends JFrame{
private JPanel P1;
private JPanel P2;
private JPanel P3;
private JButton btnFrame1;
private JButton btnFrame2;
private JButton button1;
private JTextField thisIsPanel3TextField;
private JButton btn2Frame1;
private final JFrame frame = new JFrame("MyMain Frame");
public MyMainForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(P1);
pack();
setSize(1000,800);
//setLocation(null);
btnFrame1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P1.setVisible(false);
setContentPane(new MyMainForm().P2);
}
});
btnFrame2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P2.setVisible(false);
setContentPane(new MyMainForm().P3);
}
});
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P3.setVisible(false);
setContentPane(new MyMainForm().P2);
}
});
btn2Frame1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P1.setVisible(false);
setContentPane(new MyMainForm().P3);
}
});
}
public static void main(String[] args) {
MyMainForm MyMainForm = new MyMainForm();
MyMainForm.setVisible(true);
}
}
'''
I can display P2 or P3 with this new code example above. When i try to go from P2 or P3 back to P1 the content pane doesn't show? Do i need to revalidate the content pane for this to work? I really need to be able to go from P1 to P2
The easiest way to do this is to use a CardLayout. Just follow this example:
JFrame frame = new JFrame();
JPanel p1 = new JPanel();
p1.setBackground(Color.RED);
JPanel p2 = new JPanel();
p2.setBackground(Color.WHITE);
JPanel p3 = new JPanel();
p3.setBackground(Color.BLUE);
//Create the panel that contains the "cards".
JPanel cards = new JPanel(new CardLayout());
cards.add(p1, "Panel 1");
cards.add(p2, "Panel 2");
cards.add(p3, "Panel 3");
// Add your card container to the frame
Container pane = frame.getContentPane();
pane.add(cards, BorderLayout.CENTER);
JButton btn = new JButton("Click me!");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.next(cards);
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(btn);
pane.add(btnPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
Alternatively, you can switch to a specific panel by calling cl.show(cards, "Panel X") where X is the number of the panel. This is because the swing argument is the name I assigned to each "card" and the show method recalls panels added to CardLayout by name. For your example, each button should have a listener that uses this method to "show" its assigned panel.
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 think some how my actionListeners are messed up. I am supposed to have two blocks of buttons.
First panel is 16 buttons x 16 buttons(256 buttons total). Second panel is 8 buttons x 2 buttons(16 buttons total) I am able to pass "blue" from "ColorChooser" to both panels.
However, the second panel should turn RED. NOT BLUE. My second issue - Panel 2 looks correct. It starts at 1 and goes to 16. However, Panel 1 starts at 17 and goes to 256. Please and thank you for any help.
I was also wondering why my tool tips for the button arrays do not work?
Thanks Again!
example of what I mean
final JFrame MaineFrame = new JFrame("Kola Color Crapper");
MaineFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MaineFrame.setPreferredSize(new Dimension(400, 400));
final JFrame PatternGeneratorFrame = new JFrame("Pattern Generator");
PatternGeneratorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener PatternMakerActionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
PatternGeneratorFrame.setVisible(true);
}
};
JButton PatternMakerBtn = new JButton("Make Pattern");
PatternMakerBtn.addActionListener(PatternMakerActionListener);
PatternMakerBtn.setToolTipText("This will allow you to create your own patterns 1 frame at a time.");
JPanel contentPane = new JPanel();
ActionListener myActionListener = new ActionListener() {
public void actionPerformed(ActionEvent aef) {
if (aef.getSource() instanceof JButton) {
((JButton) aef.getSource()).setBackground(ColorChooser.PassColor);
}
}
};
ActionListener ColorChooserActionListener = new ActionListener() {
public void actionPerformed(ActionEvent aee) {
if (aee.getSource() instanceof JButton) {
((JButton) aee.getSource()).setBackground(Color.red);
}
}
};
JButton button[] = new JButton[256];
JPanel GridPanel = new JPanel();
GridPanel.setBorder(BorderFactory.createLineBorder(Color.blue, 2));
GridPanel.setLayout(new GridLayout(16, 16, 10, 10));
for (int i = 0; i < button.length; i++) {
button[i] = new JButton(Integer.toString(i + 1));
button[i].addActionListener(myActionListener);
GridPanel.add(button[i]);
GridPanel.setToolTipText("lets make noise.");
}
contentPane.add(GridPanel);
JButton ColorPickerBtn[] = new JButton[16];
JPanel ActionPanel = new JPanel();
ActionPanel.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 6));
ActionPanel.setLayout(new GridLayout(2, 8, 0, 10));
for (int l = 0; l < 16; l++) {
ColorPickerBtn[l] = new JButton(Integer.toString(l+ 1));
ColorPickerBtn[l].addActionListener(ColorChooserActionListener);
ColorPickerBtn[l].setToolTipText("Choose the color you would like to use. * Colors 1-8 are static. You may change colors 9-16.");
ActionPanel.add(button[l]);
}
contentPane.add(ActionPanel);
MaineFrame.getContentPane().add(PatternMakerBtn);
PatternGeneratorFrame.setContentPane(contentPane);
PatternGeneratorFrame.pack();
PatternGeneratorFrame.setVisible(false);
MaineFrame.pack();
MaineFrame.setVisible(true);
;
}
});
}
}
}
My approach to this problem would be to just use one single ActionListener that would be listening to the entire frame.
Hi I'm having trouble in my code. I can't call or display my JPanel(TruthTable) inside my splitpane in the Minimize class when I click the button and Keypressed(Enter).The problem is in the class Minimize
*UPDATE: I'have solved my problem regarding to diplaying the panel my next problem is when I call the constructor the text in the panel should be updated.I also change the setText to append 'coz they say that JPanel doesnt support setText.I've already used,validate,repaint method but no luck in updating the textArea.
Heres my code for class Minimize:
package splashdemo;
public class Minimize extends JPanel implements ClipboardOwner
{
simButton.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent ae)
{
LogicGates lg= new LogicGates();
lg.geth();
sim s=new sim();
s.InputExp(lg.g,lg.g1);
s.menu();
s.setSize(700,700);
s.setVisible(false);
Frame f = new Frame();
Panel panel = new Panel();
f.add(BorderLayout.SOUTH, panel);
f.add(BorderLayout.CENTER, new sim());
f.add(BorderLayout.SOUTH, panel);
f.setSize(580, 500);
panel.add(s.button);
f.show();
f.setVisible(false);
JOptionPane.showMessageDialog(null, b);
ex=b;
cAppend();
JOptionPane.showMessageDialog(null, ex1);
InToPost(ex1);
foutput= doTrans();
JOptionPane.showMessageDialog(null, foutput);
TruthTable_1 kl = new TruthTable_1(foutput);
Minimize mi = new Minimize();
s.InputExp(lg.g,lg.g1);
s.menu();
lg.gatessplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mi, lg.p1);
//here's the splitpane where I should display the TruthTable_1 panel but it doesn't diplay
lg.p1.add(lg.gatessplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, s,kl));
lg.gatessplit.setOneTouchExpandable(true);
lg.gatessplit.setDividerLocation(250);
lg.gatessplit.setPreferredSize(new Dimension(900, 500));
lg.createAndShowGUI();
}});
}
Heres my code the TruthTable_1:constructors
public TruthTable_1() {
super();
tableArea.append("This is a Test");
//setBackground(Color.black);
createg();
setVisible(true);
}
public void createg(){
setLayout(new BorderLayout());
line= 0;
truth= 'T';
fallacy= 'F';
final JPanel top= new JPanel();
input= new TextField(35);
TFCheck= new Checkbox("Select for \"1/0\" (default\"T/F\")");
check= new JButton("Check");
check.addActionListener(this);
top.add(input);
top.add(TFCheck);
top.add(check);
top.setVisible(false);
tableArea= new JTextArea(16, 40);
tableArea.setEditable(false);
tableArea.setFont(new Font("Lucida Console", Font.PLAIN, 14));
// all letters are the same width in this font
go= new JButton("Do it to it!");
go.addActionListener(this);
input.addActionListener(this);
go.setVisible(false);
add(top, BorderLayout.NORTH);
scrolls= new JScrollPane(tableArea);// add scroll buttons to the area
add(scrolls, BorderLayout.CENTER);
add(go, BorderLayout.SOUTH);
setSize(535, 500);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(100, 100);
}
public TruthTable_1(String f){
createg();
tableArea.append(run(f));
}