At the moment, i have a table that has no row values when it is built, rows are added in after i click the add button. when i click the add button, it will add a row to the table and there are cells for the user to key in values. And then when i click the save button it will store each of the col value into an object. I just wanted to know if there is a more efficient way to do it instead of my if else.
package UI;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
public class TableManage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 4353951253754938210L;
private JPanel contentPane;
private JTable tablemanage;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TableManage frame = new TableManage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TableManage() {
#SuppressWarnings("unused")
DefaultTableModel manageModel;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
DefaultTableModel model=new DefaultTableModel(
new Object[][] {
},
new String[] {
"NAME", "AGE", "GENDER"
}
);
tablemanage = new JTable(model);
JScrollPane managementpane=new JScrollPane(tablemanage);
managementpane.setBounds(40, 11, 355, 118);
contentPane.add(managementpane);
JButton btnAdd = new JButton("ADD");
btnAdd.setBounds(40, 164, 89, 23);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.addRow(new Object [][] {{null, null,null}});
model.setValueAt(null,tablemanage.getRowCount()-1,0);
}
});
contentPane.add(btnAdd);
JButton btnRemove = new JButton("REMOVE");
btnRemove.setBounds(172, 164, 89, 23);
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(tablemanage.getSelectedRow()<0)
{
JOptionPane.showMessageDialog(null,"Select value To Remove");
}
else
{
model.removeRow(tablemanage.getSelectedRow());
}
}
});
contentPane.add(btnRemove);
JButton btnSave = new JButton("SAVE");
btnSave.setBounds(306, 164, 89, 23);
contentPane.add(btnSave);
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int nu=tablemanage.getRowCount();
int co=tablemanage.getColumnCount();
tablemanage.getSelectionModel().clearSelection();
int i;
int j;
ArrayList<TestingObject> testList=new ArrayList<TestingObject>();
TestingObject test=new TestingObject();
for( i=0;i<nu;i++)
{
test=new TestingObject();
for( j=0;j<co;j++)
{
System.out.println(j);
if(j==0){
test.setName((String) tablemanage.getModel().getValueAt(i,j));
}
else if(j==1){
test.setAge((String) tablemanage.getModel().getValueAt(i,j));
}
else{
test.setGender((String) tablemanage.getModel().getValueAt(i,j));
}
}
testList.add(test);
System.out.println ();
}
for(int k=0;k<testList.size();k++){
testList.get(k).print();
}
}
});
}
}
just remove inner for-loop inside btnSave action lister and put this codes
because your column count is always 3
test=new TestingObject();
test.setName((String) tablemanage.getModel().getValueAt(i,0));
test.setAge((String) tablemanage.getModel().getValueAt(i,1));
test.setGender((String) tablemanage.getModel().getValueAt(i,2));
testList.add(test);
and use this standard code it can be used with jdk 1.8 to print array list values
testList.stream().forEach((var) -> {
System.out.println(var);
});
Related
I have my original text field in my first frame and I need it to be displayed in my other jframe. The code is:
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
'nameL' is the textbox the user enters their name in.
This code describe where it should be displayed:
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
this is my first class where the user inputs their name
public order(String para){
getComponents();
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class frame1 {
public JFrame frame;
public JTextField nameL;
public JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1 window = new frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setEnabled(false);
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GRAY);
frame.setForeground(Color.WHITE);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
}
}
);
btnContinue.setBounds(0, 249, 450, 29);
frame.getContentPane().add(btnContinue);
JTextArea txtrPleaseEnterYour = new JTextArea();
txtrPleaseEnterYour.setEditable(false);
txtrPleaseEnterYour.setBackground(Color.LIGHT_GRAY);
txtrPleaseEnterYour.setBounds(0, 0, 450, 32);
txtrPleaseEnterYour.setText("\tPlease enter your name and email below\n If you do not have or want to provide an email, Leave the space blank");
frame.getContentPane().add(txtrPleaseEnterYour);
JTextArea txtrEnterYourFull = new JTextArea();
txtrEnterYourFull.setEditable(false);
txtrEnterYourFull.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtrEnterYourFull.setBackground(Color.GRAY);
txtrEnterYourFull.setText("Enter your full name");
txtrEnterYourFull.setBounds(52, 58, 166, 29);
frame.getContentPane().add(txtrEnterYourFull);
nameL = new JTextField();
nameL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}
);
nameL.setBackground(Color.LIGHT_GRAY);
nameL.setBounds(52, 93, 284, 26);
frame.getContentPane().add(nameL);
nameL.setColumns(10);
JTextArea txtroptionalEnterYour = new JTextArea();
txtroptionalEnterYour.setEditable(false);
txtroptionalEnterYour.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtroptionalEnterYour.setBackground(Color.GRAY);
txtroptionalEnterYour.setText("(Optional) Enter your email");
txtroptionalEnterYour.setBounds(52, 139, 193, 29);
frame.getContentPane().add(txtroptionalEnterYour);
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(52, 180, 284, 26);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
}
my second class where the text field has to be set
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class order extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
order frame = new order();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public order() {
setAlwaysOnTop(false);
setTitle("Order Details // Finalization");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 451, 523);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Submit Order");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlwaysOnTop(true);
JOptionPane.showMessageDialog(null, "Your Order Has Been Confirmed", "enjoy your meal", JOptionPane.YES_NO_OPTION);
}
});
btnNewButton.setBounds(164, 466, 117, 29);
contentPane.add(btnNewButton);
}
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
}
}
Open both JFrames, have them listen to the EventQueue for a custom "string display" event.
Wrap the string to be displayed in a custom event.
Throw that on the event queue, allowing both the JFrames to receive the event, which they will then display accordingly.
---- Edited with an update ----
Ok, so you're a bit new to Swing, but hopefully not too new to Java. You'll need to understand sub-classing and the "Listener" design pattern.
Events are things that Components listen for. They ask the dispatcher (the Swing dispatcher is fed by the EventQueue) to "tell them about events" and the dispatcher then sends the desired events to them.
Before you get too deep in solving your problem, it sounds like you need to get some familiarity with Swing and its event dispatch, so read up on it here.
So I'm revising a random number generator I made a while back and instead of making it in JOptionPane, I decided to try to create it in JFrame. The 2 problems I'm having is:
I can't figure out how to access the number of attempts in class "Easy" to use for class "PlayAgain".
How could I loop back to the beginning of the program and start at the Menu screen again if they decide to click btnPlayAgain? Creating a new instance of Menu does not work the way I want it to, as the Menu frame doesn't close after you choose a difficulty.
The code is for the 3 classes, Menu, Easy, and PlayAgain. I didn't include the code for buttons Medium or Hard as it is pretty much identical to Easy.
Menu
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Menu extends JFrame {
private JPanel contentPane;
public static Menu frame;
public static Easy eFrame;
public static Medium mFrame;
public static Hard hFrame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new Menu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Menu() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 149);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblSelectADifficulty = new JLabel("Select a difficulty");
lblSelectADifficulty.setBounds(10, 49, 424, 19);
lblSelectADifficulty.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblSelectADifficulty.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblSelectADifficulty);
JLabel lblRandomNumberGuessing = new JLabel("Random Number Guessing Game");
lblRandomNumberGuessing.setHorizontalAlignment(SwingConstants.CENTER);
lblRandomNumberGuessing.setFont(new Font("Tahoma", Font.PLAIN, 22));
lblRandomNumberGuessing.setBounds(10, 11, 424, 27);
contentPane.add(lblRandomNumberGuessing);
JButton btnEasy = new JButton("Easy (0-100)");
btnEasy.setBounds(10, 79, 134, 23);
contentPane.add(btnEasy);
JButton btnMedium = new JButton("Medium (0-1000)");
btnMedium.setBounds(155, 79, 134, 23);
contentPane.add(btnMedium);
JButton btnHard = new JButton("Hard (0-10000)");
btnHard.setBounds(300, 79, 134, 23);
contentPane.add(btnHard);
btnEasy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
eFrame = new Easy();
eFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
}
}
Easy
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Easy extends JFrame {
private JPanel contentPane;
private JTextField textField;
private int rand;
public int attempts;
public Easy() {
attempts = 1;
Random rnd = new Random();
rand = rnd.nextInt(100 + 1);
setResizable(false);
setTitle("Take a guess");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 300, 135);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JLabel lblGuessANumber = new JLabel("Guess a number between 0 - 100");
lblGuessANumber.setBounds(10, 11, 274, 19);
lblGuessANumber.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblGuessANumber.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblGuessANumber);
textField = new JTextField();
textField.setBounds(20, 41, 110, 20);
contentPane.add(textField);
textField.setColumns(10);
final JButton btnGuess = new JButton("Guess");
btnGuess.setBounds(164, 41, 110, 20);
contentPane.add(btnGuess);
final JLabel label = new JLabel("");
label.setFont(new Font("Tahoma", Font.PLAIN, 12));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(10, 72, 274, 24);
contentPane.add(label);
btnGuess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if((Integer.parseInt(textField.getText())) >= 0 && (Integer.parseInt(textField.getText())) <= 100){
if((Integer.parseInt(textField.getText())) < rand){
label.setText("You guessed too low.");
System.out.println(rand);
attempts++;
}
else if((Integer.parseInt(textField.getText())) > rand){
label.setText("You guessed too high.");
attempts++;
}
else if((Integer.parseInt(textField.getText())) == rand){
dispose();
PlayAgain pl = new PlayAgain();
pl.setVisible(true);
}
}
else
label.setText("Please enter a valid input.");
}
});
}
public int returnAttempts(){
return attempts;
}
}
PlayAgain
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class PlayAgain extends JFrame {
private JPanel contentPane;
public PlayAgain() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 240, 110);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblPlayAgain = new JLabel("Play Again?");
lblPlayAgain.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblPlayAgain.setHorizontalAlignment(SwingConstants.CENTER);
lblPlayAgain.setBounds(10, 27, 214, 23);
contentPane.add(lblPlayAgain);
JButton btnYes = new JButton("Yes");
btnYes.setBounds(10, 49, 89, 23);
contentPane.add(btnYes);
JButton btnQuit = new JButton("Quit");
btnQuit.setBounds(135, 49, 89, 23);
contentPane.add(btnQuit);
//Need to return number of attempts from Easy.java in lblYouGuessedCorrectly
JLabel lblYouGuessedCorrectly = new JLabel("You guessed correctly! Attempts: ");
lblYouGuessedCorrectly.setHorizontalAlignment(SwingConstants.CENTER);
lblYouGuessedCorrectly.setBounds(10, 11, 214, 14);
contentPane.add(lblYouGuessedCorrectly);
btnYes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Need to start the program over again, starting with from the Menu screen
}
});
btnQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
Suggestions:
You're creating an event-driven Swing GUI, and so you won't "loop" back to the beginning of your program as you would in a linear console program, because that's not how event driven programs work. Rather you'd simply display the menu view when needed, usually in response to some event such as within the ActionListener of a JButton and/or JMenuItem.
So add a reset JButton or JMenuItem or both, have them share the same ResetAction AbstractAction, and inside of that Action, re-show the menu view.
Side recommendation 1 (not related to your main problem): Don't use null layouts or setBounds as that will lead to rigid hard to debug and enhance GUI's that look good on one platform only.
Side recommendation 2: Don't code towards creation of JFrames but rather JPanel views as this will increase the flexibility of your program greatly, allowing you to swap JPanel views if need be using a CardLayout, or displaying views within a JFrame or JDialog or anywhere else they're needed.
For example using a CardLayout to swap JPanel views and a JOptionPane to get user input on re-starting:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class Main2 extends JPanel {
private MenuPanel menuPanel = new MenuPanel(this);
private GamePanel gamePanel = new GamePanel(this);
private CardLayout cardLayout = new CardLayout();
public Main2() {
setLayout(cardLayout);
add(menuPanel, MenuPanel.NAME);
add(gamePanel, GamePanel.NAME);
}
public void setDifficulty(Difficulty difficulty) {
gamePanel.setDifficulty(difficulty);
}
public void showCard(String name) {
cardLayout.show(Main2.this, name);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Main2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class MenuPanel extends JPanel {
public static final String NAME = "menu panel";
private static final String MAIN_TITLE = "Random Number Guessing Game";
private static final String SUB_TITLE = "Select a difficulty";
private static final int GAP = 3;
private static final float TITLE_SIZE = 20f;
private static final float SUB_TITLE_SIZE = 16;
private Main2 main2;
public MenuPanel(Main2 main2) {
this.main2 = main2;
JLabel titleLabel = new JLabel(MAIN_TITLE, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, TITLE_SIZE));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel);
JLabel subTitleLabel = new JLabel(SUB_TITLE, SwingConstants.CENTER);
subTitleLabel.setFont(subTitleLabel.getFont().deriveFont(Font.PLAIN, SUB_TITLE_SIZE));
JPanel subTitlePanel = new JPanel();
subTitlePanel.add(subTitleLabel);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, GAP));
for (Difficulty difficulty : Difficulty.values()) {
buttonPanel.add(new JButton(new DifficultyAction(difficulty)));
}
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(titlePanel);
add(subTitlePanel);
add(buttonPanel);
}
private class DifficultyAction extends AbstractAction {
private Difficulty difficulty;
public DifficultyAction(Difficulty difficulty) {
this.difficulty = difficulty;
String name = String.format("%s (0-%d)", difficulty.getText(), difficulty.getMaxValue());
putValue(NAME, name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
main2.setDifficulty(difficulty);
main2.showCard(GamePanel.NAME);
}
}
}
enum Difficulty {
EASY("Easy", 100), MEDIUM("Medium", 1000), HARD("Hard", 10000);
private String text;
private int maxValue;
private Difficulty(String text, int maxValue) {
this.text = text;
this.maxValue = maxValue;
}
public String getText() {
return text;
}
public int getMaxValue() {
return maxValue;
}
}
#SuppressWarnings("serial")
class GamePanel extends JPanel {
public static final String NAME = "game panel";
private String labelText = "Guess a number between 0 - ";
private JLabel label = new JLabel(labelText + Difficulty.HARD.getMaxValue(), SwingConstants.CENTER);
private Main2 main2;
GuessAction guessAction = new GuessAction("Guess");
private JTextField textField = new JTextField(10);
private JButton guessButton = new JButton(guessAction);
private boolean guessCorrect = false;
private Difficulty difficulty;
public GamePanel(Main2 main2) {
this.main2 = main2;
textField.setAction(guessAction);
JPanel guessPanel = new JPanel();
guessPanel.add(textField);
guessPanel.add(Box.createHorizontalStrut(10));
guessPanel.add(guessButton);
JPanel centerPanel = new JPanel(new GridBagLayout());
centerPanel.add(guessPanel);
setLayout(new BorderLayout());
add(label, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
}
public void setDifficulty(Difficulty difficulty) {
this.difficulty = difficulty;
label.setText(labelText + difficulty.getMaxValue());
}
private class GuessAction extends AbstractAction {
private int attempts = 1;
public GuessAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO use difficulty and all to check guesses, and reply to user
// we'll just show the go back to main menu dialog
guessCorrect = true; // TODO: Delete this later
if (guessCorrect) {
String message = "Attempts: " + attempts + ". Play Again?";
String title = "You've Guessed Correctly!";
int optionType = JOptionPane.YES_NO_OPTION;
int selection = JOptionPane.showConfirmDialog(GamePanel.this, message, title, optionType);
if (selection == JOptionPane.YES_OPTION) {
textField.setText("");
main2.showCard(MenuPanel.NAME);
} else {
Window window = SwingUtilities.getWindowAncestor(GamePanel.this);
window.dispose();
}
}
}
}
}
I am looking for a way to save the users input from a jlist into a txt file. It's for a homework project. I have the program set up to take user input from a textfield, then it goes into the jlist once they hit the add button. The jlist has a defaultlistmodel on it, and I'm wondering if there is a way to create a save button and allow it to save the complete jlist into a .txt file.
Also, here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JProgressBar;
import javax.swing.JLabel;
public class i extends JFrame {
private JPanel contentPane;
private JTextField jTextField;
DefaultListModel ListModel = new DefaultListModel();
ArrayList<String> arr = new ArrayList <String>();
String str;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
i frame = new i();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public i() {
super("List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
jTextField = new JTextField();
jTextField.setBounds(15, 80, 168, 20);
contentPane.add(jTextField);
jTextField.setColumns(10);
final JList jList = new JList(ListModel);
jList.setBorder(new LineBorder(new Color(0, 0, 0)));
jList.setBounds(289, 54, 135, 197);
contentPane.add(jList);
JButton jButton = new JButton("Add");
jButton.setBounds(190, 79, 89, 23);
contentPane.add(jButton);
jButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String str=jTextField.getText();
ListModel.addElement(str);
jTextField.setText("");
arr.add(str);
System.out.println(arr);
}
});
JButton delete = new JButton("DELETE");
delete.setBounds(190, 162, 89, 23);
contentPane.add(delete);
delete.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent k){
ListModel.removeElement(jList.getSelectedValue());
}
});
JButton btnUp = new JButton("UP");
btnUp.setBounds(190, 125, 89, 23);
contentPane.add(btnUp);
btnUp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int index = jList.getSelectedIndex();
if(index == -1){
JOptionPane.showMessageDialog(null, "Select something to move.");
} else if(index > 0) {
String temp = (String)ListModel.remove(index);
ListModel.add(index - 1, temp);
jList.setSelectedIndex(index -1);
}
}
});
JButton btnDown = new JButton("DOWN");
btnDown.setBounds(190, 196, 89, 23);
contentPane.add(btnDown);
btnDown.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e ){
int index = jList.getSelectedIndex();
if( index == -1 )
JOptionPane.showMessageDialog(null, "Select something to move.");
else if( index < ListModel.size() - 1 ){
String temp = (String)ListModel.remove( index );
ListModel.add( index + 1, temp );
jList.setSelectedIndex( index + 1 );
}
}
});
JLabel lblItems = new JLabel("Items:");
lblItems.setBounds(290, 37, 46, 14);
contentPane.add(lblItems);
JButton btnPrint = new JButton("PRINT");
btnPrint.setBounds(190, 228, 89, 23);
contentPane.add(btnPrint);
btnPrint.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
}
}
you need use File class to save your list in that
File file = new File("c:/test/myfile.txt");
now file's created and opened!
and for write some output to file
use Formatter Class:
public class CreateFile
{
private Formatter x;
void openFile()
{
try
{
x = new Formatter("c:/myfile.txt");
System.out.println("you created a file");
}
catch(Exception e)
{
System.err.println("error in opening file");
}
}
void addFile()
{
x.format("%s %s %s\n","20","Start","Today");
}
void closeFile()
{
x.close();
}
}
as you see,addFile method accept 3 String passed to write in the file
i passed "20" , "Start" , "Today"
you can use more/less than %s , and pass user input or a list in String to write in the file.
good luck
So for class I'm suppose to make a Celsius to Fahrenheit converter GUI. With that said, it's a pretty simple and easy program to create. I want to do more with it though. What I want to do is have one window that changes depending on which radio button is selected in a buttongroup. I want the selected radiobutton for "To Fahrenheit" or "To Celsius" to update the labels for the input and output. I have tried using an actionlistener for when one is selected, but it doesn't change the labels. Am I using the wrong listener? What's the correct way to do this?
Here's my code:
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class Converter extends JFrame {
private JPanel contentPane;
private JTextField tfNumber;
private JLabel lblCelsius;
private JLabel lblFahrenheit;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Converter frame = new Converter();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Converter() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setTitle("Celsius Converter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 308, 145);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
tfNumber = new JTextField();
tfNumber.setText("0");
tfNumber.setBounds(10, 11, 123, 20);
contentPane.add(tfNumber);
tfNumber.setColumns(10);
lblCelsius = new JLabel("Celsius");
lblCelsius.setFont(new Font("Tahoma", Font.BOLD, 15));
lblCelsius.setBounds(143, 12, 127, 14);
contentPane.add(lblCelsius);
lblFahrenheit = new JLabel("Fahrenheit");
lblFahrenheit.setBounds(187, 46, 95, 14);
contentPane.add(lblFahrenheit);
final JLabel lblNum = new JLabel("32.0");
lblNum.setBounds(143, 46, 43, 14);
contentPane.add(lblNum);
final JRadioButton rdbtnF = new JRadioButton("to Fahrenheit");
rdbtnF.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnF.isSelected()) {
lblCelsius.setText("Celsius");
lblFahrenheit.setText("Fahrenheit");
}
}
});
rdbtnF.setSelected(true);
rdbtnF.setBounds(10, 72, 109, 23);
contentPane.add(rdbtnF);
final JRadioButton rdbtnC = new JRadioButton("to Celsius");
rdbtnC.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnF.isSelected()) {
lblCelsius.setText("Fahrenheit");
lblFahrenheit.setText("Celsius");
}
}
});
rdbtnC.setBounds(121, 72, 109, 23);
contentPane.add(rdbtnC);
ButtonGroup bg = new ButtonGroup();
bg.add(rdbtnF);
bg.add(rdbtnC);
JButton btnConvert = new JButton("Convert");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnF.isSelected()) {
String num = String.valueOf(convertToF(tfNumber.getText()));
lblNum.setText(num);
}
if(rdbtnC.isSelected()) {
String num = String.valueOf(convertToC(tfNumber.getText()));
lblNum.setText(num);
}
}
});
btnConvert.setBounds(10, 42, 123, 23);
contentPane.add(btnConvert);
}
private double convertToF(String celsius) {
double c = Double.parseDouble(celsius);
double fahren = c * (9/5) + 32;
return fahren;
}
private double convertToC(String fahren) {
double f = Double.parseDouble(fahren);
double celsius = (f - 32) * 5 / 9;
return celsius;
}
}
I am trying to make one column from JTable, invisible by setting width to zero but it could not happen and it remain visible to width = 15. Here is code -
public void restoreColumnWithWidth(int column, int width) {
try {
TableColumn tableColumn = table.getColumnModel().getColumn(column);
table.getTableHeader().setResizingColumn(tableColumn);
tableColumn.setWidth(width);
tableColumn.setMaxWidth(width);
tableColumn.setMinWidth(width);
tableColumn.setPreferredWidth(width);
} catch (Exception ex) {
}
}
What is wrong with the code ?
not, never to remove TableColumn from TableModel, this is wrong suggestion, instead of to use built-in method JTable#removeColumn(TableColumn aColumn),
notice, this method remove column only from View, in the model is removed column still presents, and you can revert that, visible the removed column by using JTable#addColumn(TableColumn aColumn)
EDIT
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class TableRowHeight {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame("p*s*s*s*s*t*t");
private String[] columnNames = {"one", "two", "Playing with", "four", "five",};
private String[][] data = {
{"aaaaaa", "bbbbbb", "cccccc", "dddddd", "eeeeeee",},
{"bbbbbb", "cccccc", "dddddd", "eeeeeee", "aaaaaa",},
{"cccccc", "dddddd", "eeeeeee", "aaaaaa", "bbbbbb",},
{"dddddd", "eeeeeee", "aaaaaa", "bbbbbb", "cccccc",},
{"eeeeeee", "aaaaaa", "bbbbbb", "cccccc", "dddddd",}};
private JTable table = new JTable(new DefaultTableModel(data, columnNames));
private TableColumnModel tcm = table.getColumnModel();
private Stack<TableColumn> colDeleted = new Stack<TableColumn>();
private JButton restoreButton = new JButton("Restore Column Size");
private JButton hideButton = new JButton("Set Column Size to Zero");
private JButton deleteButton = new JButton("Delete Column");
private JButton addButton = new JButton("Restore Column");
public TableRowHeight() {
table.setRowMargin(4);
table.setRowHeight(30);
table.setFont(new Font("SansSerif", Font.BOLD + Font.PLAIN, 20));
JScrollPane scrollPane = new JScrollPane(table);
for (int i = 0; i < (tcm.getColumnCount()); i++) {
tcm.getColumn(i).setPreferredWidth(100);
}
table.setPreferredScrollableViewportSize(table.getPreferredSize());
restoreButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tcm.getColumn(2).setPreferredWidth(100);
}
});
hideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tcm.getColumn(2).setPreferredWidth(000);
}
});
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.getColumnCount() > 0) {
TableColumn colToDelete = table.getColumnModel().getColumn(table.getColumnCount() - 1);
table.removeColumn(colToDelete);
table.validate();
colDeleted.push(colToDelete);
addButton.setEnabled(true);
} else {
deleteButton.setEnabled(false);
}
}
});
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (colDeleted.size() > 0) {
table.addColumn(colDeleted.pop());
table.validate();
deleteButton.setEnabled(true);
} else {
addButton.setEnabled(false);
}
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(hideButton);
btnPanel.add(restoreButton);
btnPanel.add(deleteButton);
btnPanel.add(addButton);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(btnPanel, BorderLayout.SOUTH);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
TableRowHeight frame = new TableRowHeight();
}
});
}
}
EDIT2
you have to check too
JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JTable.getTableHeader().setReorderingAllowed(false);
If it should be removed, and not just hidden: Remove it from the table-model.
If it only should be hidden and later shown, you can remove the TableColumn from the TableColumnModel
Making the column height 0 is a bit bogus.