I searched on stack overflow for the similar answers for my question, but neither of them helped me.
So my problem is the following:
I have a main JFrame called Main_Window, on which I have a JTable and a JButton. After clicking the Button another JFrame (Update_Window) opens from Which I can update the table. The Update_Window JFrame has two TextFields and a SUBMITButton.
Briefly, I want to update my JTable in the Main_Window from the Update_Window JFrame. After I type something in the TextFields and Submit with the Button, the data should appear in the Main_Window's JTable, but it is not working.
This is my Main_Window JFrame:
private void updateBtnActionPerformed(java.awt.event.ActionEvent evt) {
Update_Window newWindow = new Update_Window();
newWindow.setVisible(true);
newWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void putDataIntoTable(Integer data, int row, int col) {
jTable1.setValueAt(data,row,col);
}
This is my Update_Window JFrame:
private void submitBtnActionPerformed(java.awt.event.ActionEvent evt) {
quantity = Integer.parseInt(quantityTextField.getText());
price = Integer.parseInt(priceTextField.getText());
Main_Window mw = new Main_Window();
mw.putDataIntoTable(price,3,2);
}
I think my problem is here Main_Window mw = new Main_Window();, because this creates a new Instance and it doesn't add the data to the correct window, or something like that.
Yes, you are right. The line Main_Window mw = new Main_Window(); is definitely wrong.
Better solution is:
public class UpdateWindow extends JFrame {
private final MainWindow mainWindow;
public UpdateWindow(MainWindow mainWin) {
mainWindow = mainWin;
}
private void submitBtnActionPerformed(java.awt.event.ActionEvent evt) {
quantity = Integer.parseInt(quantityTextField.getText());
price = Integer.parseInt(priceTextField.getText());
mainWindow.putDataIntoTable(price,3,2);
}
}
Also you need to correct the call of constructor for UpdateWindow
private void updateBtnActionPerformed(java.awt.event.ActionEvent evt) {
UpdateWindow newWindow = new UpdateWindow(this);
newWindow.setVisible(true);
newWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
Please note: I've corrected your class names as it proposed by Java naming convention. Main_Window -> MainWindow, Update_Window -> UpdateWindow.
When my suggestion don't solve your problems, please provide a [mcve] so we can better identify your problems.
Related
I have a main window called MainFrame which is a jForm to which I update the data depending on a timer, but the problem is that I cannot update the data in the same MainFrame after using the jdialog, since I end up creating another duplicate window, but with the data changed, one with the original timer and the other with the new timer, I know that I can close the first window with dispose() and then keep the second, but I would like to avoid changing windows so much
the code with which I create another window when pressing the jDialog button is the following
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String textoFieldTimer = jTextField1.getText();
int timeUserConfig = Integer.parseInt(textoFieldTimer);
Timer timeDefault = new Timer(timeUserConfig, null);
TokenAccess token = new TokenAccess();
token.access_code = code;
MainFrame mainFrame = new MainFrame(token);
mainFrame.setVisible(true);
mainFrame.timeDefault.stop();
mainFrame.timeDefault = timeDefault;
mainFrame.setUpdateTime(timeUserConfig);
this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
Is there any alternative to update the window? something like mainFrame.update(); or maybe send the value of the jTextField from the jDialog to mainFrame? since the previous code creates another MainFrame for me.
Method main setLabel and Timer.start/stop
public void setUpdateTime(int timeUserConfig) {
this.timeUserConfig = timeUserConfig;
if (timeUserConfig == 0) {
timeDefault.start();
timeDefault.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
setLabelText();
String timeUserConfigStr = Integer.toString(timeDefaultInt);
tiempoActualizado.setText("Tiempo de Actualizado: " + timeUserConfigStr+"ms");
}
});
} else {
timeDefault.stop();
timeDefault = new Timer(timeUserConfig, null);
timeDefault.start();
timeDefault.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
setLabelText();
String timeUserConfigStr = Integer.toString(timeUserConfig);
tiempoActualizado.setText("Tiempo de Actualizado: " + timeUserConfigStr+"ms");
}
});
}
}
setLabelText is a method set of label
public void setLabelText() {
String humedadStr = String.valueOf(humedad);
String temperaturaStr = String.valueOf(temperatura);
String presionStr = String.valueOf(co2);
temporalHum.setText(humedadStr);
temporalTemperatura.setText(temperaturaStr);
temporalPresion.setText(presionStr);
}
Any help would be appreciated.
Thanks for the update, and I found another solution without using an OptionPane from this question: programmatically close a JPanel which is displayed in JDialog.
I cannot replicate your codings
Start with the MainFrame, assuming you opened the JDialog by clicking on a button and wants to setText() to label lbSomething:
private void btInputActionPerformed(java.awt.event.ActionEvent evt) {
// Open new JDialog when button is clicked
NewJDialog dialog = new NewJDialog(new javax.swing.JFrame, true);
dialog.setVisible(true);
// Get user input from JDialog
String temp = dialog.getInput();
if (temp != null) {
/*
* Perform jButton1ActionPerformed() content here
* Including timeUserConfig, timeDefault and setUpdateTime() here
* so that you don't have to access mainFrame in the JDialog.
*/
lbSomething.setText(temp);
}
}
Then about the JDialog (with simple input detection):
public class NewJDialog extends javax.swing.JDialog {
// Set the variable as class variable
private String textTOFieldTimer;
public NewJDialog(java.awt.Frame parent, boolean modal) {
// default contents
}
#SupressWarinings("unchecked")
private void initComponents() {
// default contents
}
private void btSaveAction Performed(java.awt.event.ActionEvent evt) {
// Check if input correct and whether to disable JDialog
if (tfInput.getText.length() != 0) {
input = tfInput.getText();
// Connect to the whole JDialog by getWindowAncestor()
Window window = SwingUtilities.getWindowAncestor(NewJDialog.this);
// Just setVisible(false) instead of dispose()
window.setVisible(false);
} else {
JOptionPane.showMessageDialog(this, "Wrong Input");
}
}
public String getInput() {
return textToFieldTimer;
}
// default variables declarations
}
Hope this answer helps you well.
Would be better if you displayed the source code, but a simple solution to update values to an existing JFrame is by using setText() and getText().
For example:
String input = JOptionPane.showInputDialog(this, "Nuevo valor");
lbPresionActual.setText(input);
If you created a self-defined JDialog, it is about to transfer the input value when closing the JDialog, and that could be a different question.
I am coding a module for Netbeans where I have a button that when clicked will open a JFrame.
This is the action listener class of the button:
// ... (package and imports)
#ActionID(
category = "File",
id = "org.myorg.readabilitychecker.ReadabilityActionListener"
)
#ActionRegistration(
iconBase = "org/myorg/readabilitychecker/google.png",
displayName = "#CTL_ReadabilityActionListener"
)
#ActionReference(path = "Toolbars/File", position = 0)
#Messages("CTL_ReadabilityActionListener=Readability")
public final class ReadabilityActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFrame readabilityFrame = new ReadabilityFrame();
readabilityFrame.setVisible(true);
}
}
In the JFrame I basically have:
public static void main(String args[]) {
* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ReadabilityFrame().setVisible(true);
}
});
}
It also has some other automatically generated code, but nothing important.
When I run the application, the button appears in the toolbar, but when I click it, the JFrame doesn't open.
I tried checking if a print inside the actionPerformed() method would show in the output terminal and it does, so I guess that I am missing something while calling the JFrame.
Can anyone give me a hint on where the problem is?
I think the issue is with the object creation of your frame. Try
ReadabilityFrame readabilityFrame = new ReadabilityFrame();
readabilityFrame.setVisible(true);
Hope it helps.
I found where was the problem.
The method initComponents() automatically generated had the line setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); and it was always throwing an exception.
I just changed EXIT_ON_CLOSE to DISPOSE_ON_CLOSE, defined the frame in a different way and now, the problem disappeared.
I have a jframe (DuasPaginas2) that opens when I click the "next" button that is in another jframe (DuasPaginas), and in the second jFrame (DuasPaginas2) I have a comboBox (cbx3) that conforms to the option I Choose Place a value in a text field (txtValor) and then have another text field in a user name and enter a value (txtValue1).
And my question is this: having a button on the first jframe (DuasPaginas) that allows me to do an add operation and then presents me the value in jlabel (jLabelResultado), how do I use the variables (txtValor and txtValor1) introduced In the second jframe (DuasPaginas2) to do the sum with the button in the first jFrame?
If possible help me with examples because my knowledge in java is not very advanced.
Second jFrame (DuasPaginas2)
private void cbx3ActionPerformed(java.awt.event.ActionEvent evt) {
int resultado = 0;
String i = cbx3.getSelectedItem().toString();
if(i.equals("baixo"))resultado=1;
else if(i.equals("medio"))resultado=2;
else if(i.equals("alto"))resultado=3;
txtValor.setText(String.valueOf(resultado));
}
Jframe DuasPaginas
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DuasPaginas2 obj = new DuasPaginas2();
obj.setVisible(true);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
int valorUm=0;
int valorDois=0;
int valorFinal=0;
valorUm = Integer.parseInt(txtValor1.getText());
valorDois = Integer.parseInt(txtValor.getText());
valorFinal=valorUm+valorDois;
jLabel1.setText(valorFinal+"");
}
The button to do the sum operation on the first jframe.
Give me error on this part.
I am trying to step through a ArrayList<JPanel> which contains ChartPanels. The Next button correctly steps through the charts as expected, but when I click the Previous button nothing happens. I feel like my logic may be convoluted. Thanks!
Note: panelCombination is a JPanel.
Code for the buttons:
public static int advance = 0;
public static ArrayList<JPanel> chartList = new ArrayList<>();
private void NextMouseClicked(java.awt.event.MouseEvent evt) {
panelCombination.removeAll();
panelCombination.add(chartList.get(advance));
panelCombination.validate();
if (advance < chartList.size()-1) {
advance++;
}
}
private void PreviousMouseClicked(java.awt.event.MouseEvent evt) {
if (advance > 0) {
advance--;
}
panelCombination.removeAll();
panelCombination.add(chartList.get(advance));
panelCombination.validate();
}
Use a CardLayout to change views, instead of trying to remove and add panels. What you're trying to do can easily be accomplished by calling the next() and previous() methods of the CardLayout. All you really need to do is set the layout of your panelCombination to CardLayout, add all you panels to the panelCombination and use those methods
CardLayout layout = new CardLayout();
panelCombination.setLayout(layout);
// add all panels.
....
private void PreviousMouseClicked(java.awt.event.MouseEvent evt) {
layout.previous(panelCombination);
See more at How to Use CardLayout
Also from the looks of you method signatures, it looks like you are using NetBeans GUI Builder. You can see How to Use CardLayout with Netbeans GUI Builder
In case anyone else has this issue in the future: the code that I used after reading through the javadoc and links peeskillet provided:
public class ResultsFrame extends javax.swing.JFrame {
public static CardLayout switchPanels;
/**
* Creates new form ResultsFrame
*/
public ResultsFrame() {
initComponents();
switchPanels = new CardLayout();
panelCombination.setLayout(switchPanels);
getPDDGraph();
//getProfileGraph();
}
private void NextMouseClicked(java.awt.event.MouseEvent evt){
switchPanels.next(panelCombination);
}
private void PreviousMouseClicked(java.awt.event.MouseEvent evt) {
switchPanels.previous(panelCombination);
}
public static void getPDDGraph() {
.....
JFreeChart chart = new JFreeChart(xyplot);
ChartPanel chartPanel = new ChartPanel(chart);
panelCombination.add(chartPanel);
}
Thanks again, it was much easier than what I was doing before and more condensed!
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class JDorm implements ItemListener{
public static void main(String[] args){
JCheckBox privateroom = new JCheckBox("Private Room",false);
JCheckBox interweb = new JCheckBox("Internet Connection",false);
JCheckBox cable = new JCheckBox("Cable TV connection",false);
JCheckBox fridg = new JCheckBox("Refridgerator",false);
JCheckBox microwave = new JCheckBox("Microwave",false);
JCheckBox soon = new JCheckBox(",and so on",false);
JLabel greet = new JLabel("Please choose ammenities");
String sel = "Your selected options";
JTextArea textBox = new JTextArea(sel,0,1);
cable.addItemListener();
JFrame dormFrame = new JFrame("Dorm Options");// creates frame with title
final int WIDTH = 250;
final int HEIGHT = 500;
dormFrame.setSize(WIDTH, HEIGHT);// sets the size of frame in pixels
dormFrame.setVisible(true);// note: default visibility is false
dormFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dormFrame.setLayout(new FlowLayout());
dormFrame.add(greet);
dormFrame.add(microwave);
dormFrame.add(fridg);
dormFrame.add(cable);
dormFrame.add(interweb);
dormFrame.add(privateroom);
dormFrame.add(soon);
dormFrame.add(textBox);
}
public void itemStateChanged(ItemEvent event){
Object source = event.getSource();
int select = event.getStateChange();
}
}
This is what I have so far, I know I need listeners, and a message to appear in the box when selection is checked and unchecked.
Do I need if statements for the changes?
Create a generic listener that can be added to all the check boxes. Something like:
ItemListener listener = new ItemListener()
{
public void itemStateChanged(ItemEvent event)
{
JCheckBox checkBox = (JCheckBox)event.getSource();
textBox.setText( checkBox.getText() );
}
};
Then you add the listener to each check box:
privateRoom.addItemListener( listener );
interweb.addItemListener( listener );
I have tried for one Checkbox and you can do others similarly
final JCheckBox privateroom = new JCheckBox("Private Room",false);
Now add item listener to checkbox privateroom and also the actions which you would like to happen i.e.
privateroom.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent event)
{
if (event.getItemSelectable() == privateroom)
textBox.setText("Private Room");
}
});
The reason i have declared Checkbox privaterroom as final is because privaterroom is local and is being accessed from an inner class.
One more thing I don't know the way you have written your program is good or bad because I am also learning swing and am a newbie. But the way i write my program has the following structure
class MyClass extends JFrame implements LISTENER_NAME
{
// Components declared here
// constructor starts
public MyClass()
{
//Componenets instantiated
// add listeners to appropriate components
// setVisible(), setDefaultCloseOperation(),setSize() etc called
}
// listener interface methods here like
public void itemStateChanged(ItemEvent ie)
{
................
}
// main method
public static void main(String[] args)
{
new MyClass();
}
} // class over
This way I have never encountered the final keyword etc problems. I hope some expert will guide us.