Hi I have a JButton defined like:
private JButton btnExp;
private JPanel jpShow = new JPanel();
jpShow.setLayout(null);
btnExp = new JButton("Export");
btnExp.setBounds(100, 250, 120, 25);
jpShow.add(jspTable);
jpShow.add(btnExp);
//Adding Panel to Window.
getContentPane().add(jpShow);
public void actionPerformed(ActionEvent ae) {
try{
Object obj = ae.getSource();
if (obj == btnExp) {
FileWriter excel = new FileWriter("File.TSV");
for(int i = 0; i < dtmCustomer.getColumnCount(); i++){
excel.write(dtmCustomer.getColumnName(i) + "\t");
}
excel.write("\n");
for(int i=0; i< dtmCustomer.getRowCount(); i++) {
for(int j=0; j < dtmCustomer.getColumnCount(); j++) {
excel.write(dtmCustomer.getValueAt(i,j).toString()+"\t");
}
excel.write("\n");
}
excel.close();
JOptionPane.showMessageDialog(this, "File Written","Success", JOptionPane.PLAIN_MESSAGE);
}
}catch(Exception e){
System.out.println(e);
}
}
Am trying to get the JTable to be exported after the user clicks the button but nothing happens and no exception is raised. Am I doing it the wrong way?
You are not adding the ActionListener to your button correctly. The correct way is:
btnExp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// add here the contents in your actionPerformed method
}
})
The code you post will not even compile
You should add the ActionListener to your JButton as #Dan already showed in his answer
You should make sure you close the FileWriter in a finally block. Now, when an exception occurs it will not be closed
You will end up with a non-responsive UI if you export the table on the Event Dispatch Thread. Consider using a SwingWorker. Consult the Concurrency in Swing tutorial for more information
Avoid the use of setLayout( null ) and setBounds. Use a decent LayoutManager instead
Related
First of all, I want to ask you to ask as much information as possible to me to be able to help me out.
I've been creating an automatic reminder system which is able to create the reminder in PDF then automatically send it to the clients which you've chosen to be reminded.
The program is working perfectly fine, but once I try to start it on another computer, it does not work anymore. The following problems occur:
On one computer in Eclipse it does not even open the frame which handles the user input (telling the program which clients have to be reminded). The code is given below. An interesting point here is that I've tried to print a line if the actionPerformed method is running. It does NOT appear at all. So for some reason it is not listening to that whole method.
if(starter.getAccess().equals("admin") || starter.getAccess().equals("god")){
menu = new JMenu("Aanmaningen");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Debiteuren aanmanen");
menuBar.add(menu);
menu.addSeparator();
ButtonGroup group2 = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("Pyxis Distribution B.V.");
rbMenuItem.setSelected(false);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group2.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem.addActionListener(new ActionListener() {
#SuppressWarnings("static-access")
#Override
public void actionPerformed(ActionEvent arg0) {
chosenComp = true;
f.getContentPane().add(new Main());
f.revalidate();
f.repaint();
Distrscherm obj = new Distrscherm();
obj.plannerJTable();
}
});
On the other computers it was jarred and did open the menu, but did the JComboBox did not automatically complete the searchterms. It neither sent the mail. When clicking on the button save and send it didn't do anything. The codes are shown below.
This is the code which handles automatic completion (pretty basic code)
public AutoComboBox() {
setModel(new DefaultComboBoxModel(myVector));
setSelectedIndex(-1);
setEditable(true);
JTextField text = (JTextField) this.getEditor().getEditorComponent();
text.setFocusable(true);
text.setText("");
text.addKeyListener(new ComboListener(this, myVector));
setMyVector();
}
/**
* set the item list of the AutoComboBox
* #param patternExamples an String array
*/
public static void setKeyWord(Object[] patternExamples) {
AutoComboBox.keyWord = patternExamples;
setMyVectorInitial();
}
private void setMyVector() {
int a;
for (a = 0; a < keyWord.length; a++) {
myVector.add(keyWord[a]);
}
}
private static void setMyVectorInitial() {
myVector.clear();
int a;
for (a = 0; a < keyWord.length; a++) {
myVector.add(keyWord[a]);
}
This is the code which handles the SAVE button
#Override
public void actionPerformed(ActionEvent e) {
#SuppressWarnings("unused")
Writer obj1 = new Writer(getTableData(table), "./planningdagelijks/week.csv");
for(int i =0; i < model.getRowCount(); i++) {
Datareader.Runner(model.getValueAt(i, 0));
internalfile obj2 = new internalfile();
obj2.intern();
try {
maildata.Reader((String)model.getValueAt(i, 0));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Pdfgenerator.Filegenerator((String)model.getValueAt(i, 0));
}
}
});
I've implemented code that will - amongst other things - make a series of JButton's disabled after being clicked. The code for this is below:
ActionListener disableButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (!(event.getSource() instanceof JButton)) {
return;
}
theModel.currentWord.append(event.getActionCommand());
wordDisplay.setText(theModel.getCurrentWord());
((JButton) event.getSource()).setEnabled(false);
}
};
theModel.randomLetters();
for (int i = 0; i < 16; i++) {
dice = new JButton(theModel.letters.get(i));
dice.addActionListener(disableButton);
boggleGrid.add(dice);
}
Notice the "((JButton)event.getSource()).setEnabled(false);" line. This, after completing the previous lines, makes any clicks on the button inactionable. I wish to reverse this when a seperate button is clicked. It's code is below:
JButton submitWordButton = new JButton("Submit Word");
submitWordButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent submit) {
wordDisplay.setText("");
theModel.currentWord.delete(0, 16);
((JButton) submit.getSource()).setEnabled(true);
}
});
info.add(submitWordButton, BorderLayout.SOUTH);
My dilemma is I don't know how to reference the JButton's outside of the ActionListener that disables them once clicked and hence enabled them again. The button I want to use to do this (the one with code most recently pasted above) is in another class. Any ideas?
I've been making a bus booking project and I've made a booking page.
The JPanel named PanelSeat and it contains buttons (about 36 buttons) inside.
I want to check if any button inside JPanel is clicked, then disable the button and finally if a user clicks util 3 buttons, it will be stopped or a user can't click it anymore.
This is the code I've written so far:
private void CountTicket() {
try {
int count = 3;
Component[] components = PanelSeat.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JButton) {
if (((JButton) components[i]).isSelected()) { // I wanna check if any button is clicked by a user
if (JOptionPane.showConfirmDialog(this, "Seat Confirmation") == JOptionPane.YES_OPTION) { // confirm message
((JButton) components[i]).setEnabled(false); // disable the button
count--;
System.out.println("Your ramaining seat : " + count);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
How do I check if button has been clicked?
Since you want to count how many times a button was pressed, and then disable it with counts involved I would suggest that you wrap the Jbutton class in order to make performing those tasks easier, this solution is generally better
class JbuttonWrapper extends JButton {
int count=0;
public void increment()
{
count++;
if (count==numberOfclicksToDisable)
{
this.setEnabled(false);
}
}
}
//then you can simply do the following.
JbuttonWrapper [] buttons= new JbuttonWrapper [NumbersOfButtonsYouHave];
for (int i=0; i<=NumbersOfButtonsYouHave;i++)
{
buttons[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttons[i].increment(); } });
}
and this solution is based on your code
static int count=3;
Component[] components = PanelSeat.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JButton) {
{
components[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
count--;
}
});
}
Add ActionListener to JButton, check example here.
I am trying to create and simple program that has the user input 4 fields using the JFrame and textfields. Save those into a class. Put that class into an ArrayList (So they have the option to delete / or add more "classes" to it later). Then display all the contents of the ArrayList on one Frame.
I got the four fields to work I believe , but the part where the ArrayList contents are supposed to be displayed is not working ( I get a blank frame ).
this is my add into the arrayList ..
public void newEntryFrame()
{
JFrame entryFrame = new JFrame("Passafe");
entryFrame.setVisible(true);
entryFrame.setSize(500, 500);
entryFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
entryFrame.setLocationRelativeTo(null);
entryFrame.setLayout(new FlowLayout());
header.setFont(new Font("Serif", Font.BOLD, 16));
entryFrame.add(header);
entryFrame.add(nameLabel);
entryFrame.add(nametf);
entryFrame.add(usernameLabel);
entryFrame.add(usernametf);
entryFrame.add(passwordLabel);
entryFrame.add(passwordtf);
entryFrame.add(descriptionLabel);
entryFrame.add(descriptiontf);
entryFrame.add(enterButton);
enterButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == enterButton)
{
name = nametf.getText();
description = descriptiontf.getText();
username = usernametf.getText();
password = passwordtf.getText();
totalEntries++;
JOptionPane.showMessageDialog(null, "SAVED");
}
else if(source == okButton)
{
JOptionPane.showMessageDialog(null, "Ok Button Works");
}
}
this is what I have to display the arrayList.
public void viewEntryFrame()
{
JFrame viewFrame = new JFrame("Passafe");
viewFrame.setSize(500, 500);
viewFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
viewFrame.setLocationRelativeTo(null);
viewFrame.setLayout(new FlowLayout());
viewFrame.add(listHeader);
newEntry tempView = new newEntry();
for(int i = 0; i < totalEntries; ++i)
{
tempView = entries.get(i);
viewFrame.add(tempView.display);
}
viewFrame.add(okButton);
okButton.addActionListener(this);
viewFrame.setVisible(true);
}
I might be doing this completely wrong if so could you point me in the right direction.
I don't think you ever called setContentPane() A JFrame has only one component in the main part of it. You have to create a JPanel to which you can add all of the components you want, then add that to your JFrame.
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(/**whatever you want in your JFrame**/);
//...
panel.add(/**whatever you want in your JFrame**/);
frame.setContentPane(panel);
You never seem to be adding anything to your entries list...
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == enterButton)
{
name = nametf.getText();
description = descriptiontf.getText();
username = usernametf.getText();
password = passwordtf.getText();
totalEntries++;
// Nope, nothing here...
JOptionPane.showMessageDialog(null, "SAVED");
}
//...
}
Also, this is very dangrouos...
newEntry tempView = new newEntry();
for(int i = 0; i < totalEntries; ++i)
{
tempView = entries.get(i);
viewFrame.add(tempView.display);
}
Rather the relying on the actual side of the ArrayList, you relying on some other variable, which may or may not equal the actual size, instead you should be using ArrayList#size, for example
for(int i = 0; i < entries.size(); ++i)
{
newEntry tempView = entries.get(i);
viewFrame.add(tempView.display);
}
Or if you're using Java 5+...
for(newEntry tempView : enties)
{
viewFrame.add(tempView.display);
}
When I run my program using eclipse only one button shows up (top left corner) but when I use javac in terminal (most of the time) all buttons show up! It's really bugging me. Can anyone help? Thanks!This is my constructor:
public TicTacToe(){
super("Farm Tic-Tac-Toe");
setSize(450,750);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cont = getContentPane();
cont.setLayout(null);
int newLine = 0;
int lineCount = 0;
for(int i = 0; i < buttons.length; i++){
buttons[ i] = new JButton(blank);
if(i == 3 || i == 6){
newLine++;
lineCount = 0;
}
buttons[ i].setBounds(lineCount*150,newLine*150,150,150);
cont.add(buttons[ i]);
buttons[ i].addActionListener(this);
lineCount++;
}
}
and here's the action listener...
public void actionPerformed(ActionEvent e){
for(int i = 0; i < buttons.length; i++){
if(e.getSource()==buttons[ i]){
if(turn%2==0){
buttons[ i].setName("x");
buttons[ i].setIcon(x);
buttons[ i].removeActionListener(this);
}
else{
buttons[ i].setName("o");
buttons[ i].setIcon(o);
}
buttons[ i].removeActionListener(this);
}
}
turn++;
checkWin();
}
Please don't tell me too much about how my code design is bad because I am (not a beginner, but) not too good at Java.
You're calling setVisible(true) before adding all of your components to the GUI, so it is not showing them all. Don't do this. Instead call setVisible(true) after all components have been added.
Also
As has been suggested by many, don't use null layout, but instead learn about and use the layout managers.
Yeah, get another book.
The solution to the problem is really very simple...
The first one is the lack of a layout manager and the other is the order in which you are displaying your UI (as has already being stated)
public class SimpleTicTacToe {
public static void main(String[] args) {
new SimpleTicTacToe();
}
public SimpleTicTacToe() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new GamePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class GamePane extends JPanel {
public GamePane() {
setLayout(new GridLayout(3, 3));
for (int index = 0; index < 9; index++) {
add(new JButton());
}
}
}
}
Take the time to read through Creating a GUI With JFC/Swing to gain a grasp of the basics.
The Eclipse GUI only renders buttons that are drawn in certain very specific ways. If your code does it differently (for example, with a Loop), Eclipse won't be able to draw it.
Also, use a LayoutManager, don't do things like .setLayout(null)