My code consists of three classes, say: x(extends JFrame), y(extends JPanel) and z. x has the main function. It has borderLayout and has two panels in it: left and center. Left panel has bunch of JButtons and JTextFields where user inputs his values and those values are used to draw some things into my center panel handled by my y class.
The z class is used by the y class for general calculation purposes. Now I am almost done making the program and am working on a "clear" button in my left panel which will clear all the text user has entered and what has been drawn into my center panel (handled by y class).
What i can do is set some values to their default values and repaint() my center panel but the problem is that there are a LOT of variables and then there are again a lot of variables in my z class(which is instantiated by y).
This is getting confusing and tiresome so i am thinking if there is any way i can (i am going against the rules of garbage collection here) i can kill the instance of y in my x class and make a new one. That will be so neat. Tell me what i should do in such situation. Thanks.
EDIT: i want the clear button to remove what has already been drawn into my panel so can i do this in my x class?
remove(myRightpanelInstance);
myRightPanel myRightpanelInstance2 = new myRightPanel();
add(myRightpanelInstance2, BorderLayout.CENTER);
it doesnt work btw.
Based on your edit you want to add a new panel and overwrite the old one. You can simply:
MyRightPanel myRightPanelInstance2 = new myRightPanel();
add(myRightPanelInstance2, BorderLayout.CENTER);
This will overwrite the existing panel with the new one.
Make sure this code is in your listener for the clear button. This only happens if you call this code inside the listener.
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Either above code here or above code in a method and method call here
}
})
Related
Im using NetBeans to do a work for school. There i have an huge JPanel that contains a huge JFrame. That JFrame as 5 small JFrames, 1 is the menu with buttons, the other ones are boxes with text that will swap when i choose in the buttons.
When one box is showing the other ones are invisible im using the following code (dont know if it is the best):
public ConversorUI() {
initComponents();
PanelVazio.setVisible(true);
PanelTemp.setVisible(false);
PanelComp.setVisible(false);
PanelMoedas.setVisible(false);
this.pack();
}
My problem is, when i run my program i have a big space with nothing and only below it the components appear. I want them to appear in the top of my window. What can I do ?
ANSWER
After some time searching i just realized i could Set Layout from JPanel to Card Layout and create JPanels over each other activating them with the code:
private void DinheiroButtonActionPerformed(java.awt.event.ActionEvent evt) {
//Remove Panels
CAIXA.removeAll();
CAIXA.repaint();
CAIXA.revalidate();
//Add Panels
CAIXA.add(DinheiroBox);
CAIXA.repaint();
CAIXA.revalidate();
}
Looks like you are using Java Swing , right ?
Any way you do something wrong if you have JPanel that contains JFrames. To build correct UI you have to add JPanels inside JFrame.
Also, to reach correct component order and placing you need configure corresponded layout, here is description.
You can load one jframe at e time
Because every jframe you added have own place and visibility doesnt do anything to remove
Try to save every jframe and for changing
Delete old one and add new one
Why are you using multiple JFrames to do this? From what I can see it would be a better idea to use JPanels that can take care of the individual tasks, such as the menu and buttons etc.
I'm relatively new to using javax.swing myself, but from my knowledge you can only have 1 frame at a time per window (like the other person said).
From what i've been able to discern from your project, you possibly don't even need multiple panels. You just need one panel for the menu with buttons, and multiple Labels or JLabels that display text according to the button. You can use the setText method in writing your addActionListener, something like this:
buttonName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
labelName.setText("blah blah blah");
//and whatever else you may need to do
}
});
The following method has the end result I need. The problem is, when the method is called, the starting pnlMain stays visible until the new pnlMain is created and replaces the original.
The point of this method is to change the panel by creating a new one but this process takes a little time, so I am trying to have the "load" panel show up during that time.
public void changePanel() {
remove(pnlMain);
add(load);
repaint();
pnlMain = new HunterPanel(settings); // HunterPanel extends JPanel
remove(load);
add(pnlMain);
repaint();
pnlMain.requestFocus();
}
"Changing Panels during runtime"
The correct way is to use a CardLayout that will allow you to switch between views. See How to Use CardLayout for more details. See a simple example here
But just to let you know where you're going wrong in your code, if you remove and add components at runtime, you need to revalidate(). But in your case, go with the CardLayout. After you learn it, you be happy you did :-)
Sorry about this question but I have been struggling with an assignment my professor gave us for days and have no idea where to begin. I don't want someone to do it for me or anything, I am just looking to learn/get some good pointers because I can't find a foothold in this at all.
The assignment is as follows :
Implement a graphical user interface with the GridLayout class with a 10 5 grid of JButtons and JLabels. The JButtons should be on the top five rows and the JLabels should be on the next five rows. (The first JButton should have the text 1-1 and the last the text 5-5.) The JButton on the i th row and j th column should have the text i - j on it. The text of the JLabels should be 0.
The purpose of the JLabels is to count the clicks of the corresponding JButtons. For example, when a user clicks button
i - j for the first time, the text of the JLabel of the (5 + i )th row and j th column should change to 1.
You are not allowed to use any instance variables.
Hint 1: use and inner class for the labels.
Hint 2: you can increment the “number” the label by getting the text of the label, parsing it to an int with Integer.parseInt( ), and by changing the text of the label.
You must also add one more JButton which resets the counters on the JLabels. The
text on the JButton should be reset.
So far I have just been studying notes with no understanding or cluelessly typing away and come up with a completely non-functioning desperate attempt which is as follows :
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class NewFrame extends JFrame {
private static JButton[] buttons;
public static void main ( String[] args ) {
NewFrame frame = new NewFrame( );
}
public void NewFrame( ){
JFrame frame = new JFrame ("JFrame");
JPanel panel = new JPanel( );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
int noOfButtons = 25;
buttons = new JButton[ noOfButtons ];
for(int i = 0; i<buttons.length ; i++){
buttons[i] = new JButton();
panel.add(buttons[i]);
JLabel label = new JLabel( "Initial Text" );
}
frame.getContentPane( ).add( panel );
frame.setSize( 500, 500);
frame.setVisible( true );
}
}
Can someone please offer me some advice or hints here as I have been struggling with this for an age ?
Please have a look at this link: So, You Need to Write a Program but Don't Know How to Start which will give you great tips on how to start. The key is to break down your big problem into small steps and then try to solve each step in isolation. Then if you get stuck at least you'll be able to post a much more specific question, one that is more easily answered with a specific and helpful answer. Another good resource are the Swing tutorials which can show you how to use the various Swing components including JFrames, JPanels, JButtons, text components, and what not. You can find them here: Using Swing Components
Best of luck!
Edit 1:
Your code now compiles but there are two glaring issues that first need to be fixed:
1) Your class has no constructor but rather a "pseudo-constructor". Remember constructors have no return type, not even void.
2) You don't use a GridLayout.
Other issues: again the key is to break the problem down. I recommend you do just that on paper, and then type your version of the steps you think you need to solve the problem. Then we can go through them one at a time.
Generally, when you write a Swing application, your main class extends JFrame. You do all the initialization / create the buttons / etc in the constructor, then create an instance of the class in main()
-- edit --
see hovercraft's comment - you don't have to do the following in the constructor of an extended JFrame. Just change this to your JFrame variable if you do it externally.
The java documentation is your best friend - use it. http://download.oracle.com/javase/6/docs/api/
Create a GridLayout object, assign it to your content pane (this.getContentPane()) with setLayout
Create your buttons / labels, add those to the content pane
etc, etc
Look at the documentation for JButton.setActionCommand, JButton.addActionListener
You can access the labels later to increment / reset them with this.getContentPane().getComponents(), or one of the other access methods
Before I look at the code, you will surely need the Java tutorials on buttons and actions:
http://download.oracle.com/javase/tutorial/uiswing/components/button.html
http://download.oracle.com/javase/tutorial/uiswing/misc/action.html
The first issue with your code is that you use an instance variable to store the buttons in an array. You don't need this, since you are already adding them to the panel immediately.
The second issue is actually getting your buttons to do stuff when clicked. You need to add an ActionListener of your own design to each button, as follows:
myButton = new JButton();
myButton.addActionListener(new MyButtonListener());
and declare some MyButtonListener:
public class MyButtonListener implements ActionListener
{
}
the contents of the ActionListener class are beyond the scope of my help for your homework. But the Java tutorials are a great resource if you have no idea how to implement ActionListener.
I need help implementing the following behavior: when a user double-clicks on a row in the JTable on JPanel A — code snippet for this shown below — the program should redirect the user to JPanel B. B should contain some data about whatever was on the JTable's row.
private void TableMouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getClickCount() == 2){
System.out.println("Double click");
}
}
What do you mean, "redirect the user to?"
If the other panel is already visible, you can switch the focus there (though that's a bit unusual behavior which may negatively surprise your user) using setFocus() on the second panel.
If the other panel is not visible but has its own space in the GUI, then I guess you'd simply make it visible. If it has to overlay the panel the user just clicked on, then you want to use a CardLayout to display two panels alternatively in the same space.
Check out this thread: http://forums.sun.com/thread.jspa?threadID=366670
This is essentially the same thing you are trying to do, you just want to respond to mouse double-clicks instead of mouse move events.
I need to display different drawings on a JPanel.
I have put the drawing files into an array, but when I changed it using a button, the JPanel only displays first drawing and doesn't change to the next drawing...
I have called panel.revalidate(), but it doesnt work.
This is the segment of the code that I used but not working.
The JPanel display was static.
String[] a = {"image1.txt","image2.txt","image3.txt"};
List<String> files = Arrays.asList(a);
public void actionPerformed(ActionEvent e) {
if (e.getSource() == answer1){
fileNumber++;
//call other class for painting (files=array files, fileNumber=index of the array)
draw = new drawingPanel(files,fileNumber);
panel.add(draw);
}
panel.revalidate();
panel.repaint();
}
You might try keeping a reference to your drawingPanel and calling remove() on the existing drawingPanel before re-adding it. According to the JPanel JavaDoc, the layout is FlowLayout by default - which will not replace the image like you are intending, but will instead place the next drawingPanel to the right of the previous one. (what happens when you resize the window?)
By the way, how do you handle the case where you get past the last image in the array?
Are you only displaying one drawing at a time? If so, you may want to try using a CardLayout, so you can switch between drawings easily. See http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html for an example.
I had a similar issue the other day attempting to dynamically display different buttons on my UI depending which tab of a JTabbedPane the user picked. CardLayout was just the thing to make things easy.