printing a method onto a JPanel - java

So i have been trying to print a method onto a Jpanel with no success, the method works on the console but i cant get it to print to the Jpanel, I am fairly new to Java, so if you have any advice could you keep it fairly simple :D. I have tried several solutions to similar questions on here to no avail here is the Code.
public class fizzbuzz {
private static MouseEvent fizzBuzz() {
String fizz = "Fizz";
String buzz = "Buzz";
String fB = "Fizz buzz";
int num = 0;
while(num <= 100) {
num++;
if (num % 3 == 0 && num % 5 != 0) {
System.out.println (fizz);
}
else if (num % 5 == 0 && num % 3 != 0) {
System.out.println (buzz);
}
else if (num % 3 == 0 && num % 5 == 0){
System.out.println (fB);
}
else {
System.out.println(num);
}
}
return null;
}
public static void ShowGUI(String[] args) {
JPanel displayPanel = new JPanel();
JButton okButton = new JButton("Start count");
okButton.setFont(new Font("Malina Light", Font.TRUETYPE_FONT, 14));
final JLabel Jlab = new JLabel();
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Jlab.getToolTipText(fizzBuzz());
}
});
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
content.add(okButton, BorderLayout.SOUTH);
content.add(Jlab, BorderLayout.NORTH);
JFrame window = new JFrame("Gui test");
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(250, 250);
window.setLocation(100, 100);
window.setVisible(true);;
}
public static void main(String[]args){
//fizzBuzz();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ShowGUI(args);
}
});
}
}

Here:
Jlab.getToolTipText(fizzBuzz());
that is absolute nonsense. This call will invoke your static method, yes. But beyond that it does nothing to get text into your JLabel.
The javadoc for getToolTipText() says:
Returns the tooltip location in this component's coordinate system.
Hint: try jLabel.setText("some string"); instead.
And then: decide what you want to do: either you want to print to the console (as your fizzBuzz() method does) or you update UI elements.
Beyond that: read about java naming conventions. Class names go UpperCase, and variables/fields go camelCase. By deviating from such standards you make reading your source code much harder.
And the real answer is: don't just call some method because you maybe assume it makes sense. When you write code, each character, each keyword, each and every thing do matter. Don't write something down that you do not understand. Instead - read the corresponding documentation for example. Learning Swing UIs by trial/error will not work - that stuff is simply too complicated to get right. Thus: start reading here for example to learn how to work with JLabels.

First of all:
private static MouseEvent fizzBuzz() {
What is the point of the above method signature? Why would you ever return a MouseEvent. The method has nothing to do with a mouse.
So i have been trying to print a method onto a Jpanel with no success
Where? I don't see any logic in your code that attempts to do this. In any case you don't display text on the panel, you display text in a component that you add to the panel.
So start by reading the Swing Tutorial for Swing basics.
Start with the section on How to Use Text Areas. There is demo code you can download that shows you how to append text to a text area.
You can then try the section on How to Write a MouseListener. Again the demo code shows how to add text to the text area when a MouseEvent is generated.
Using these two examples should help you better structure your code and allow you to append text to a text area instead of use System.out.println(...).

Related

How to create multiple buttons that do the same on different positions without creating actual new buttons?

Im really new to java and Programming as a whole. In school, I decided to work on a project to raise my grade, and as simple java is currently our topic i decided on trying to recreate battleships in a jframe using swing. I've made some good progress so far but im stuck on a quality of Life Problem.
So basically, in the editor we use (Java Editor ( javaeditor.org )) i use swing to implement buttons etc. in the jframe. As im gonna need a lot of Buttons for the games gui, I want to do it, so i dont have to make several buttons which have to be filled in with the arguments. What im trying to do is have some arguments create several buttons for me so they dont actually all need their own “method“ as all buttons have to basically do the exact same thing.
I tried searching for similar things on google but I couldnt find anything, so i decided to create this account to ask if someone might be able to help me with this Problem. If something isnt understandable feel free to ask (English isnt my mother tongue so some parts might be hard to understand).
Looking forward to any replies! Thanks in advance for helping.
Initially I thought I could use a for-loop to create these multiple buttons but there would always be some kind of error with the ActionPerformed argument.
for (int i = 0;i > 25;i++ ) {
jButton[i].setBounds(48, 48 + i, 113, 73);
jButton[i].setText("jButton1");
jButton[i].setMargin(new Insets(2, 2, 2, 2));
jButton[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton[i]_ActionPerformed(evt);
}
});
cp.add(jButton[i]);
}
As already said I expect there to be more than 1 button, whilst keeping the lines of code in the constructor as short as possible.
If you're desiring a grid of buttons, then create them in a for loop, and place them in the JPanel using a GridLayout. Something like this might work:
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class ManyButtons extends JPanel {
private static final int SIDES = 10;
private JButton[][] buttonGrid = new JButton[SIDES][SIDES];
public ManyButtons() {
setLayout(new GridLayout(SIDES, SIDES));
for (int row = 0; row < buttonGrid.length; row++) {
for (int col = 0; col < buttonGrid[row].length; col++) {
String text = String.format("[%d, %d]", col + 1, row + 1);
buttonGrid[row][col] = new JButton(text);
buttonGrid[row][col].addActionListener(event -> {
String command = event.getActionCommand();
System.out.println("Button pressed: " + command);
});
add(buttonGrid[row][col]);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
ManyButtons mainPanel = new ManyButtons();
JFrame frame = new JFrame("Many Buttons");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
Also avoid setBounds and null layouts.
Regarding:
.... without creating new JButtons
This is not technically possible if you want a fully functioning button (as opposed to creating a rendered button in a JTable), however, buttons can share ActionListeners, so all buttons that do the same kind of thing (think -- all the number buttons on a calculator) can use the very same ActionListener. Alternatively, you can set a button's Action using your own class that extends from AbstractAction for even greater flexibility and power, and multiple buttons (and JMenuItems) can share the same action.

How do I make a CardLayout work with an arbitrary amount of cards?

I am trying to make cardLayout work with an arbitrary amount of cards, meaning I will need some kind of a loop through all the objects I have. Now I tried and I made it work with manually created JPanels but once I put a loop in it doesn't work.
#SuppressWarnings("serial")
public class ClassCardLayoutPane extends JPanel{
JPanel cards;
public ClassCardLayoutPane() {
initialiseGUI();
}
private void initialiseGUI() {
String[] listElements = {"A2", "C3"};
cards = new JPanel(new CardLayout());
JLabel label = new JLabel("Update");
add(label);
JList selectionList = new JList(listElements);
selectionList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent evt) {
if (!evt.getValueIsAdjusting()) {
label.setText(selectionList.getSelectedValue().toString());
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, label.getText());
}
}
});
// The panels created by this loop don't work, the cards get stuck on the first one
/*
for (int i = 0; i < listElements.length-1; i ++) {
JPanel temp = new JPanel();
temp.add(new JLabel(i+""));
cards.add(temp, listElements[i]);
}*/
JPanel card1 = new JPanel();
card1.add(new JTable(20,20));
JPanel card2 = new JPanel();
card2.add(new JTable(10,20));
cards.add(card1, listElements[0]);
cards.add(card2, listElements[1]);
//the panels here do work. I don't know what I'm doing wrong
add(selectionList);
add(cards);
}
public static void main(String[] args) {
JFrame main = new JFrame("Win");
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setPreferredSize(new Dimension(1366, 768));
main.getContentPane().add(new ClassCardLayoutPane());
main.pack();
main.setVisible(true);
}
}
Okay so the commented out for loop is what doesn't work for me which has me really confused? Can someone explain to me why it doesn't work and how I could make it work? By the way, listElements can be a different size, that's what I'm trying to get working because eventually, listElements will start off as a LinkedList, so when I create the array for the ListItems, it will be a different size every time because I don't know how many items there will be. Can someone please help me make this work? By "It doesn't work", I mean when I use the loop, the JPanel gets stuck on the very first card and doesn't switch to the next card anymore! There is no error message, the program runs fine but it doesn't do what it's meant to do which is switch cards! Note that when I do them individually, the program works perfectly! Thank you.
Okay so the commented out for loop is what doesn't work for me which has me really confused?
Well the first thing you should be doing is adding debug code to the loop to see if unique card names are being used.
If you did that then you would notice the following problem:
for (int i = 0; i < listElements.length-1; i ++) {
Why are you subtracting 1 fro the list length? You only ever add one panel to the CardLayout.
The code should be:
for (int i = 0; i < listElements.length; i ++) {
When code doesn't execute as you think you need to add debug code or use a debugger to step through the code to see if the code executes as you expect.
You can't just always stare at the code.

press buttons one by one

Hello I am new to java language,and I have created a JFrame in NetBeans IDE 8.2 .
The JFrame contains 8 buttons created diretly from swing palette.The case is that I am trying to open another JFrame form after clicking for example 5 buttons.
I know that for appearing another JFrame form it is used setVisible(true) method, in the last btnActionPerformed;
What I am asking is that how to make possible clicking 5 buttons and then appear the other Jframe form??If somebody knows what I am asking please help me to find the solution?
You could have a counter variable that each time you clic on a button it increases by 1 its value and when that value is 5, you call setVisible on your second JFrame.
However I suggest you to read The use of multiple JFrames, Good / Bad practice?. The general consensus says it's a bad practice.
As you provided not code, I can only show you that it's possible with the below image and the ActionListener code, however you must implement this solution on your own:
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (e.getSource().equals(buttons[i][j])) {
clics++;
sequenceLabel.setText("Number of Clics: " + clics);
if (clics == 5) {
clics = 0;
frame2.pack();
frame2.setLocationRelativeTo(frame1);
frame2.setVisible(true);
}
}
}
}
}
};

How do you change contents of a JPanel based on a previously selected JButton?

I'm making an interface for a community. The options include "Add Person", "Add to Family" and "Remove Member from Family". I thought making multiple JPanels was very time consuming so I made the JPanel dependent on the user's "choice". For example,
if(choice == 1)
{
addPTitle = new JLabel("ADD PERSON");
addPTitle.setHorizontalAlignment(SwingConstants.CENTER);
addPTitle.setBounds(75,20,350,50);
addPTitle.setFont(calibri);
addPTitle.setForeground(red);
}
else if(choice == 2)
{
addPTitle = new JLabel("ADD TO FAMILY");
addPTitle.setHorizontalAlignment(SwingConstants.CENTER);
addPTitle.setBounds(75,20,350,50);
addPTitle.setFont(calibri);
addPTitle.setForeground(red);
}
else if(choice == 3)
{
addPTitle = new JLabel("REMOVE MEMBER");
addPTitle.setHorizontalAlignment(SwingConstants.CENTER);
addPTitle.setBounds(75,20,350,50);
addPTitle.setFont(calibri);
addPTitle.setForeground(red);
}
It works fine when I change the value of choice manually but when I tried adding an ActionListener for the buttons themselves, the value of choice didn't change and the contents of the JPanel that were displayed were still based from the value I set manually. Here's my code for the ActionListener:
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource() == "ADD PERSON")
{
choice = 1;
frame.setContentPane(addP);
frame.invalidate();
frame.validate();
}
else if(e.getSource() == "ADD TO FAMILY"){
choice = 2;
frame.setContentPane(addP);
frame.invalidate();
frame.validate();
}
else if(e.getSource() == "REMOVE MEMBER FROM FAMILY"){
choice = 3;
frame.setContentPane(addP);
frame.invalidate();
frame.validate();
}
e.getSource() return an object. You are trying to compare it to a string. Instead you can use e.getActionCommand() (assuming you haven't changes the action command)
Also in case you're temped, don't compare strings with ==. Use equals
if ("ADD PERSON".equals(e.getActionCommand()) {}
Or if your buttons scope are accessble in the ActionListener you can compare the object,
if (e.getSource() == addPersonButton) {}
Another option, in case for any reason you did change the action command you can also use the text of the button to compare
JButton button = (JButton)e.getSource();
String text = button.getText();
if ("ADD PERSON".equals(text)) {}
SIDE NOTE
You should look into using a CardLayout that lets you change views. You say creating extra panels is time consuming, but debugging problems like this may be even more time consuming ;) See this simple CardLayout example and see How to use CardLayout
you should revalidate you panel .
use Jpanel.revalidate().

JTextfield Fonts and Attributes problem

So I am creating a program that changes the JTextField depending on what the user Chooses. So its pretty much like a Word Document with fonts(from a JComboBox), sizes, and attributes(Bold...etc). Obviously mine is very small and only works with a single line(A JTextField). The Problem i'm getting is that After I've written some things down into the field with specific attributes and I want to add more words down with different attributes, it changes the whole text field rather than just the new part I added. I know the problem with it is
Writer.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
if((e.getKeyChar() >= e.VK_A && e.getKeyChar()<= e.VK_Z) || (e.getKeyChar() >= 'a' && e.getKeyChar()<='z')|| e.getKeyChar() == '\b' ) // Checks to make sure No Numbers
{
Writer.setEditable(true);
}
else
{
Writer.setEditable(false);
}
if(font.equals("Arial"))
{
if(size.equals("8"))
{
setSize = 8;
}
else if(size.equals("10"))
{
setSize = 10;
}
else if(size.equals("12"))
{
setSize = 12;
}
if(color.equals("Black"))
{
setColor = Color.BLACK;
}
else if(color.equals("Blue"))
{
setColor = Color.BLUE;
}
else if(color.equals("Red"))
{
setColor = Color.red;
}
Font font = new Font("Arial", setAttribute, setSize);
Writer.setFont(font); // I Know that this sets the font everytime, so i'm pretty sure this is where my problem is.
Writer.setForeground(setColor);
}
Any ideas on how I can make the Change so it newly entered characters can have different fonts than the previous characters.
JComponents for styled text - How to Use Editor Panes and Text Panes, examples here, here, some of examples on this forum
JTextFields allow the use of HTML. It might take a bit of work to parse and insert new html code, but you might be able to do it that way.
There's a list of WYSIWYG text editors for Java here. I especially like metaphase editor, based on Charles Bell's HTMLDocumentEditor.

Categories