adding row automatically based on user input - java

what i want to do is my table should automatically add row depends on the number of rows i input in a textbox. example if the user input 3 in the textbox and i click he clicked the jbutton the table will automatically have 3 rows with null values.. i'm just new to programming and this is a lab activity we did yesterday but no one seems did it
private JPanel contentPane;
private JTable table;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WindowwwTry frame = new WindowwwTry();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WindowwwTry() {
DefaultTableModel dm = new DefaultTableModel();
addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
table.setModel(dm);
dm.addColumn("PROCESS");
dm.addColumn("CPU Time");
dm.addColumn("Arrival Time");
}
});
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);
table = new JTable();
table.setBounds(177, 123, 1, 1);
contentPane.add(table);
textField = new JTextField();
textField.setBounds(92, 24, 86, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
int ps = Integer.parseInt(textField.getText());
for(int x=0; x<ps; x++){
dm.addRow(new Object[]{x});
}
}catch(Exception e){
e.printStackTrace();
}
}
});
btnNewButton.setBounds(206, 23, 89, 23);
contentPane.add(btnNewButton);
}

Your code works perfectly fine. The problem you experience is that you don't see the results, because the size of your table is very, very small. Change the line where you set bounds to something like this:
table.setBounds(177, 123, 200, 100);

As #gawi said your table is too small (its width and height are 1 pixel). You should set it to some higher value (I tried using table.setBounds(177, 123, 100, 100) and it fits quite nicely in the window.
Also your for loop incorrect. You want that
table will automatically have 3 rows with null values
so the for loop should look something like this
for(int x=0; x<ps; x++){
dm.addRow(new Object[]{null, null, null});
}
to set to null all the 3 columns in your table

Related

How to calculate summation values from multiple JTextFields using loop in java

I am trying to making a calculator.
Here the user can add multiple JTextFields to take his/her desired input with just one button click.
Now I want that the user will take the input in multiple JTextFields added by him and on clicking the Result button will show the sum of all. But I am always getting 0 as output.
Code:
public class Button extends JFrame {
private JPanel contentPane;
private JButton btnAdd;
private JButton btnResult;
private JTextField resultField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Button frame = new Button();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Button() {
initComponents();
}
static JTextField field = null;
//static JTextField fields[] = new JTextField[10];
private static int y = 0;
ArrayList<String> arr = new ArrayList<String>();
int ans, sum = 0;
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 527, 414);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
field = new JTextField();
field.setBounds(45, y += 60, 284, 32);
field.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(field);
contentPane.revalidate();
contentPane.repaint();
}
});
btnAdd.setBounds(170, 341, 89, 23);
contentPane.add(btnAdd);
btnResult = new JButton("Result");
btnResult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < arr.size(); i++) {
arr.add(field.getText());
sum += Integer.parseInt(arr.get(i));
}
resultField.setText(String.valueOf(sum));
}
});
btnResult.setBounds(383, 306, 89, 23);
contentPane.add(btnResult);
resultField = new JTextField();
resultField.setBounds(361, 275, 129, 20);
contentPane.add(resultField);
resultField.setColumns(10);
}
}
Please help how can I find the correct output?
Suggestions:
Again, when you create a data-entry text field, add it to the GUI and add it to an ArrayList of the data entry field type.
Then in the result button's ActionListener, iterate through this list using a for loop.
Inside of the for loop, get the entry field, get its text (via .getText() if using a JTextField), parse it to number via Integer.parseInt(...), and add it to a sum variable that is initialized to 0 prior to the for loop. Then display the result after the loop.
Also,
Best to use JSpinners that use a SpinnerNumberModel such as JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1)); instead of JTextField for number entry. This will limit the user to entering numbers only, and won't allow non-numeric text entry, a danger inherent in your current design.
Having to add your entry fields by button may be an over-complication
But if it is necessary, then best to add the spinners (or text fields if you must) to a JPanel that uses a proper layout manager, such a new GridLayout(0, 1) (variable number of rows, 1 column) and then add that to a JScrollPane so that you can see as many fields as has been entered.
If using a JSpinner, then you don't even need a "calculate result" button, since if you add a ChangeListener to each JSpinner, you can calculate the result on the fly whenever a spinner has had its data changed.
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class Button2 extends JPanel {
private List<JSpinner> spinnerList = new ArrayList<>();
private JButton resultButton = new JButton("Result");
private JButton addEntryFieldBtn = new JButton("Add Entry Field");
private JTextField resultField = new JTextField(6);
private JPanel fieldPanel = new JPanel(new GridLayout(0, 1, 4, 4));
public Button2() {
resultField.setFocusable(false);
resultButton.addActionListener(e -> calcResult());
resultButton.setMnemonic(KeyEvent.VK_R);
addEntryFieldBtn.addActionListener(e -> addEntryField());
JPanel topPanel = new JPanel();
topPanel.add(addEntryFieldBtn);
topPanel.add(resultButton);
topPanel.add(new JLabel("Result:"));
topPanel.add(resultField);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(fieldPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(centerPanel);
scrollPane.setPreferredSize(new Dimension(300, 300));
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane);
}
private void calcResult() {
int sum = 0;
for (JSpinner spinner : spinnerList) {
sum += (int) spinner.getValue();
}
resultField.setText(String.valueOf(sum));
}
private void addEntryField() {
JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
spinner.addChangeListener(evt -> {
calcResult();
});
fieldPanel.add(spinner);
spinnerList.add(spinner);
revalidate();
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Button2 mainPanel = new Button2();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}

Scroll Bar does not adjust to JPanel dimensions, Java JScrollPane

I am trying to get a scroll bar for a Panel that will get a big number of lines, however I am stuck whit this.
As you can see in my window (click here to open the picture), Scroll bars does not adjust to the panel's dimensions
Below you can see the code i am working with:
public class Config extends JFrame {
private static JPanel contentPane;
private static JScrollPane paneSiteScroll;
private static JPanel paneSite;
private JTextField txtURL;
private JButton btnAdd;
private JLabel lblName;
private JTextField txtName;
private JPanel paneBar;
/**
* Launch the application.
*/
public static void config() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Config frame = new Config();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws Throwable
*/
public Config() throws Throwable {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 550);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//Start top Add Bar
paneBar = new JPanel();
paneBar.setBounds(0, 0, 700, 35);
contentPane.add(paneBar);
paneBar.setLayout(null);
JButton btnBack = new JButton("Back");
btnBack.setBounds(1, 3, 65, 28);
paneBar.add(btnBack);
btnBack.setVerticalAlignment(SwingConstants.TOP);
JLabel lblUrl = new JLabel("URL:");
lblUrl.setBounds(80, 9, 35, 20);
paneBar.add(lblUrl);
txtURL = new JTextField();
txtURL.setBounds(115, 5, 310, 26);
paneBar.add(txtURL);
txtURL.setColumns(10);
lblName = new JLabel("Name:");
lblName.setBounds(435, 9, 47, 20);
paneBar.add(lblName);
txtName = new JTextField();
txtName.setBounds(480, 5, 155, 26);
paneBar.add(txtName);
txtName.setColumns(10);
btnAdd = new JButton("Add");
btnAdd.setBounds(635, 3, 61, 29);
paneBar.add(btnAdd);
//End top Add Bar
//Start Scroll and Panel configuration
paneSiteScroll = new JScrollPane();
paneSite = new JPanel();
paneSite.setLayout(null);
paneSite.setBounds(10, 40, 400, 600);
/*Testing different dimensions configuration*/
paneSiteScroll.setSize(new Dimension(300, 300));
paneSiteScroll.setBounds(10, 40, 300, 200);
paneSiteScroll.setPreferredSize(new Dimension(400, 300));
/*Testing different dimensions configuration*/
paneSiteScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
paneSiteScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
paneSiteScroll.getViewport().add(paneSite);
contentPane.add(paneSiteScroll);
paneSiteScroll.setVisible(true);
paneSite.setVisible(true);
//End Scroll and Panel configuration
try {
Categories.categories(paneSite); //GET CATEGORIES
} catch (Throwable e) {
e.printStackTrace();
}
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!txtURL.getText().isEmpty() || !txtName.getText().isEmpty()) {
InsertDB insert = new InsertDB();
try {
insert.insertDB("INSERT INTO sites (siUrl, siName) VALUES ('" + txtURL.getText() +"'"
+ ", '" + txtName.getText() + "')",
conn);
} catch (Exception e1) {
e1.printStackTrace();
}
}
else {
JOptionPane.showMessageDialog(null, "URL or Name cannot be empty!");
}
}
});
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Back action button
dispose();
}
});
}
}
This is my first question, I do not know what else to add, also i visited many question from stak overflow with similar problems but i couldn't figure it out.
Thanks in advance.
Finally fixed it, I restored the layout to null and added paneSite.setPreferredSize(new Dimension(600, 600)); after paneSite.setbounds. This make it work.

How can i disable jbutton when pressed 10 times

I need some help about Java GUI. I want to add 10 numbers to memory from JTextField. And when it's done JButton must gonna be disable and program must show me a message dialog. How can I do this?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Uygulama extends JFrame {
private JPanel contentPane;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Uygulama frame = new Uygulama();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Uygulama() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 233, 140);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(48, 13, 116, 22);
contentPane.add(textField);
textField.setColumns(10);
JButton btnHesapla = new JButton("HESAPLA");
btnHesapla.addActionListener(new ActionListener() {int counter = 0;
public void actionPerformed(ActionEvent arg0) {
while(counter < 9) {
counter++;
if(counter == 10) {
buton.setEnabled(false);}
}
});
btnHesapla.setBounds(58, 48, 97, 25);
contentPane.add(btnHesapla);
}
}
Add an ActionListener to your JButton if using Swing, and inside that, you'll increment a global variable by one. Then you ask if the variable is == 10 and do yourButton.setEnabled(false) or yourButton.setEnabled(counter < 10) if you're not using an if. You already have your listener set up, so it's only a matter of adding a variable you'll increment inside it and a call to setEnabled of your button.
Here's a working example with an ArrayList used to store the numbers. No need to use a global count variable here because the size of the ArrayList already tells us how many numbers we have stored :-)
public class NumbersApplication extends JFrame {
private JPanel contentPane;
private JTextField textField;
private List<Integer> numbers;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NumbersApplication frame = new NumbersApplication();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public NumbersApplication() {
numbers = new ArrayList<>();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 233, 140);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(48, 13, 116, 22);
contentPane.add(textField);
textField.setColumns(10);
JButton btnHesapla = new JButton("HESAPLA");
btnHesapla.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int number = Integer.parseInt(textField.getText());
numbers.add(number);
btnHesapla.setEnabled(numbers.size() < 10);
System.out.println(number + " has been added to memory.");
if (numbers.size() == 10) {
System.out.println("Your numbers are: " + numbers);
}
}
});
btnHesapla.setBounds(58, 48, 97, 25);
contentPane.add(btnHesapla);
}
}

Scrolling Text Pane JFrame Java

I'm trying to create a sort of log of all the keys hit, at the moment I just need to figure out how to either:
Link the position of the "text" to the scroll bar to the right
OR
Add a different component which is suited better to hold large amounts of multiple line text.
What am I doing wrong here? Thanks!
public class MacroMakerGui extends JFrame {
public static final long serialVersionUID = 1L;
public static JPanel contentPane;
public static JTextField textField = new JTextField();;
public static MacroKeyListener keylistener = new MacroKeyListener(textField);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MacroMakerGui frame = new MacroMakerGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MacroMakerGui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 126, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JButton btnNewButton = new JButton("Record Macro");
btnNewButton.setBounds(10, 220, 99, 30);
contentPane.add(btnNewButton, null);
textField.setBounds(10, 189, 99, 20);
contentPane.add(textField);
textField.setColumns(10);
JEditorPane editorPane = new JEditorPane();
editorPane.setBounds(10, 11, 84, 153);
contentPane.add(editorPane);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(93, 11, 17, 153);
contentPane.add(scrollBar);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnNewButton.addKeyListener(keylistener);
}
});
}
}
Instead of JScrollBar, use JScrollPanel. Add that to the contentPane, and add your editorPane as a chiled of the JScrollPanel.

Clicking on JButton(Bubble Sort) clears the JTextField.Why?

public class Sort_BenchMark extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnBubbleSort;
private JLabel label_1;
private JButton btnGenerate;
private JButton btnSelectionSort;
private JLabel lblSs;
private JLabel lblStatus;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
Sort_BenchMark frame = new Sort_BenchMark();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sort_BenchMark()
{
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);
textField = new JTextField("Enter ");
textField.setForeground(Color.GRAY);
textField.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent e) {
textField.setText("");
textField.setForeground(Color.BLACK);
}
});
textField.setBounds(29, 30, 139, 20);
contentPane.add(textField);
textField.setColumns(10);
label_1 = new JLabel("");
label_1.setBounds(334, 20, 120, 30);
contentPane.add(label_1);
btnBubbleSort = new JButton("Bubble Sort");
btnBubbleSort.setBounds(204, 20, 120, 30);
contentPane.add(btnBubbleSort);
btnSelectionSort = new JButton("Selection Sort");
btnSelectionSort.setBounds(204, 70, 120, 30);
contentPane.add(btnSelectionSort);
lblSs = new JLabel("");
lblSs.setBounds(334, 70, 120, 30);
contentPane.add(lblSs);
lblStatus = new JLabel("");
lblStatus.setBounds(75, 87, 93, 23);
contentPane.add(lblStatus);
final JRadioButton rdbtnAvgCase = new JRadioButton("Avg Case");
rdbtnAvgCase.setBounds(29, 150, 109, 23);
contentPane.add(rdbtnAvgCase);
ButtonGroup b = new ButtonGroup();
b.add(rdbtnAvgCase);
btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btnBubbleSort.setEnabled(true);
btnSelectionSort.setEnabled(true);
final String s = textField.getText();
if(s.contentEquals(""))
{
lblStatus.setText("Enter length");
}
else
{
lblStatus.setText("Ready");
if(rdbtnAvgCase.isSelected())
{
btnBubbleSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t1 = new Thread(new Runnable()
{
#Override
public void run()
{
btnBubbleSort.setEnabled(false);
label_1.setText("done");
btnBubbleSort.setEnabled(true);
}
});
t1.start();
}
});
btnSelectionSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t3 = new Thread(new Runnable()
{
#Override
public void run()
{
btnSelectionSort.setEnabled(false);
lblSs.setText("done");
btnSelectionSort.setEnabled(true);
}
});
t3.start();
}
});
}
}
}
});
btnGenerate.setBounds(64, 62, 88, 25);
contentPane.add(btnGenerate);
}
}
The above code is about Swing.
The actual code how i designed is:-(In the frame)
Select the Average Case (RadioButton)
Enter any number in textfield (Enter)
click on generate
click on any sort button(Bubble Sort and Selection Sort)
Now, whats the problem is, If I click on BubbleSort the text field gets cleared. But it should not happen as per I designed. Can anyone suggest me the solution so that text field wont get clear after entered anything in it?
These lines here:
#Override
public void focusGained(FocusEvent e) {
textField.setText(""); //HERE
textField.setForeground(Color.BLACK);
}
in the focus listener code says that when you click in the textfield then set its text to a empty string.
Firstly, horrible nested ActionPerformed you've got there.
That aside, Vincent Ramdhanie is right as to where the problem is originating. The reason why it only happens when you click a certain button, is because when you disable a button, then it cannot have focus, which forces the focus to be on something else, which in the disable-btnBubbleSort's case, appears to be your textfield.
Instead of btnSelectionSort.setEnabled(false) and btnSelectionSort.setEnabled(true), try using setVisible(false) and setVisible(true).
If that doesn't work, drop the onfocus-part, and do something with a mouse-click event instead.

Categories