Button click creates new JTable everytime instead of refreshing with new value - java

I'd like to create a JTable that displays the values from a created object by clicking a button.
The object is created here:
public class Getraenkeverwaltung extends Firma {
public static Getraenk getraenk1 = new Getraenk(1, "Pepsi Maxx Original", 0.99, 500);
...
}
Now with the following code I'm creating the window with all the panels.
public void buildUi() {
// Create the main window
Frame fr = new Frame();
fr.setLayout(new BorderLayout());
// Define colors
Color headerColor = new Color(38, 70, 83);
Color contentColor = new Color(42, 157, 143);
// create navigation pane at the top
JPanel navigation = new JPanel();
navigation.setBackground(headerColor);
navigation.setLayout(new GridLayout(1,4));
navigation.setPreferredSize(new Dimension(800,50));
// create content pane in the middle
JPanel content = new JPanel();
content.setBackground(contentColor);
content.setPreferredSize(new Dimension(800, 500));
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
// create footer pane at the bottom
JPanel footer = new JPanel();
footer.setBackground(headerColor);
footer.setLayout(new GridLayout(1,1));
footer.setPreferredSize(new Dimension(800, 50));
footer.setLayout(new BorderLayout());
// show impressum in the footer pane
JLabel impressum = new JLabel(Firma.impressum());
impressum.setHorizontalAlignment(SwingConstants.CENTER); // Platziert den Text mittig
impressum.setForeground(Color.white);
// create the buttons
Button btnBestand = new Button("Bestand anzeigen");
Button btnVerkauf = new Button("Verkaufen");
Button btnErhoehen = new Button("Bestand erhoehen");
Button btnExit = new Button("Exit");
// display beverages on button click
btnBestand.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String column [] = {"Artikelnummer", "Artikel", "Bestand"};
Object data [][] = {
{getraenk1.getId(), getraenk1.getName(), getraenk1.getBestand()},
{getraenk2.getId(), getraenk2.getName(), getraenk2.getBestand()},
{getraenk3.getId(), getraenk3.getName(), getraenk3.getBestand()}
};
JTable table = new JTable(data, column);
JScrollPane sp = new JScrollPane(table);
content.remove(sp);
content.revalidate();
content.repaint();
content.add(sp);
}
});
// open new sale window
btnVerkauf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Verkaufen();
}
});
// close the program
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// add the buttons to the navigation pane
navigation.add(btnBestand);
navigation.add(btnVerkauf);
navigation.add(btnErhoehen);
navigation.add(btnExit);
// add the impressum to the footer pane
footer.add(impressum, BorderLayout.CENTER);
// add the three main panels to the window
fr.add(navigation, BorderLayout.NORTH);
fr.add(content, BorderLayout.CENTER);
fr.add(footer, BorderLayout.SOUTH);
fr.pack();
}
One of the problems is the button functionality of btnBestand. Whenever I'm changing the value of some of my products, it should refresh the JTable.
Unfortunately, there's a new JTable displayed everytime I click on the button,
so it looks like this after hitting the button four times.
I'd like to just display the table with the new value after clicking on the button again.
Thanks in advance.
// edit:
Removed the content.remove(sp); pointed out by Gjermund Dahl, as it is unnecessary in this context. Thank you.
Problem still persists

Related

Creating GUI components dynamically in java

So, we can create for example a button dynamically:
panel.add(new JButton("Button"));
validate();
But the question is, how do we make calls to those elements later? For example, how do I add an event listener to this button created above, like, 100 lines of code later?
Create a variable for your JButton:
JButton jButton = new JButton("Button");
panel.add(jButton);
validate();
/*
*
*
100 lines of code
*
*/
// add an event listener
jButton.addActionListener((ActionEvent) -> {
// do something
});
I've always created my buttons before adding to the panel like so
private JPanel buttonPanel() { //button panel method containting
JPanel panel = new JPanel();
JButton addButton = new JButton("Add");
addButton.setToolTipText("Add Customer Data");
JButton editButton = new JButton("Edit");
editButton.setToolTipText("Edit selected Customer");
JButton deleteButton = new JButton ("Delete");
deleteButton.setToolTipText("Delete selected Customer");
addButton.addActionListener((ActionEvent) -> {
doAddButton();
});
editButton.addActionListener((ActionEvent) -> {
doEditButton();
});
deleteButton.addActionListener((ActionEvent) -> {
doDeleteButton();
});
panel.add(addButton);
panel.add(editButton);
panel.add(deleteButton);
return panel;
}
Allows you do something like this later on.
private void doAddButton() { //provides action for add button
CustomerForm customerForm = new CustomerForm(this, "Add Customer", true);
customerForm.setLocationRelativeTo(this);
customerForm.setVisible(true);
}
In order to bind event listeners or other functionality into the button, you'd need to store a reference to it in a variable. So, instead of
panel.add(new JButton("Button"));
You could initialize the button with
JButton myButton = new JButton("Button");
panel.add(myButton);
and then later in your code
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something
}
});

Java Button disappears after clicking

I'm trying to add a button using an JOptionPane in another button, but after I clicked the original button just keeps disappearing.
I've tried adding the JPanel manually instead of using 'handPanelNPC.getHandPanel()' by iterating through the handPanel.buttons but it stil wont work. I've checked the ArrayList size and it is already inserted properly.
LayoutTesting.java
public class LayoutTesting extends JFrame{
HandPanel handPanelNPC = new HandPanel();
public LayoutTesting(HandPanel handPanel, int type){
Container pane = getContentPane();
if (type==1){
handPanelNPC = handPanel;
}
pane.setLayout(new BorderLayout());
pane.add(handPanelNPC.getHandPanel(), BorderLayout.NORTH);
validate();
repaint();
}
public LayoutTesting(){
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(handPanelNPC.getHandPanel(), BorderLayout.NORTH);
}
}
HandPanel.java
public class HandPanel implements ActionListener{
JFrame frame = null;
JPanel panel = new JPanel();
ArrayList<JButton> buttons = new ArrayList<JButton>();
public HandPanel(){
addNewButton();
panel.setLayout(new FlowLayout());
panel.add(buttons.get(0));
}
public JComponent getHandPanel(){
panel = new JPanel();
for(int i=0; i<buttons.size(); i++){
JButton button = buttons.get(i);
panel.add(button);
}
return panel;
}
public void addNewButton(){
JButton button = new JButton();
button.setPreferredSize(new Dimension(40,58));
button.addActionListener(this);
buttons.add(button);
}
public void actionPerformed(ActionEvent e) {
String[] options = {"Summon", "Set", "Add Card"};
int messageType = JOptionPane.QUESTION_MESSAGE;
int code = JOptionPane.showOptionDialog(
frame,
"What would you like to do?",
"Card Name",
0, messageType, null,
options, options[1]);
if (code==2){
addNewButton();
LayoutTesting frame = new LayoutTesting(this, 1);
}
}
}
Main.java
public class Main extends JFrame{
public static void main(String[] args){
LayoutTesting frame = new LayoutTesting();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
You have too many odd things happening in your code to give a simple answer.
Try debugging your own code by looking at this line in HandPanel.java:
LayoutTesting frame = new LayoutTesting(this, 1);
What does it really do? Now remove that line and the button will not disappear. Now try and work out what that line was doing, and why the button disappeared.
Also 'panel.add(buttons.get(0));' does nothing because there is never a button in the array when you make that call (You add the button afterwards in another method).
Here is a rough working demo that lets you add as many new cards as you want to the first frame, and each card has a button that will let you summon a new card.
public class LayoutTesting extends JFrame{
Container pane;
//Add card when button is pressed:
public void addCard(){
Container card = new JPanel();
card.setBackground(Color.red);
JButton newButton = addNewButton();
newButton.setBackground(Color.red);
card.add(newButton);
pane.add(card);
revalidate();
repaint();
}
//Setup window and add button:
public LayoutTesting(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
setLayout(new FlowLayout());
pane = new JPanel();
pane.setLayout(new GridBagLayout());
JButton firstButton = addNewButton();
firstButton.setBackground(Color.green);
add(pane);
add(firstButton);
}
//Create button and action listener:
public JButton addNewButton(){
JButton button = new JButton();
button.setPreferredSize(new Dimension(40, 58));
button.addActionListener(new java.awt.event.ActionListener(){
#Override
public void actionPerformed(java.awt.event.ActionEvent evt){
buttonAction(evt);
}
});
return button;
}
//Action fer each button:
public void buttonAction(ActionEvent e) {
String[] options = {"Summon", "Set", "Add Card"};
int messageType = JOptionPane.QUESTION_MESSAGE;
int code = JOptionPane.showOptionDialog(
this,
"What would you like to do?",
"Card Name",
0, messageType, null,
options, options[1]);
if (code==2){
addCard();
}
}
}

Code works on windows but not on mac

I'm in the early stages of making Battleships (just started a computer science degree) and had been using Eclipse on Windows. So far I've just created the grids and have added an actionlistener to the jbuttons so they change colour when clicked.
It works fine when I run it on my Windows PC, however when I try to run it on a mac, it just shows the basic grid and doesn't change colours or anything.
Anyone had a problem like this or can help? I can't figure out why it would work on one and not the other.
Thanks
Here is my code, if that helps (I know it's not elegant or anything right now)
public class BattleshipFrame {
public static void main(String[] args) {
//creating JFrame
JFrame frame = new JFrame("Battleship");
frame.setLayout(new GridLayout(1, 3));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//creating User Panel
JPanel userpanel = new JPanel();
userpanel.setLayout(new GridLayout(10, 10));
userpanel.setSize(400, 400);
//creating JButton array
JButton[] button = new JButton[100];
//putting JButtons in User Panel
for (int i = 0; i < 100; i++) {
button[i] = new JButton();
button[i].setBackground(Color.BLUE);
userpanel.add(button[i]);
//changing colour of buttons when clicked
button[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
Object source = ev.getSource();
if (source instanceof Component) {
((Component) source).setBackground(Color.GREEN);
}
}
});
}
//creating computer panel
JPanel comppanel = new JPanel();
comppanel.setLayout(new GridLayout(10, 10));
comppanel.setSize(400, 400);
//putting JButtons in User Panel
for (int i = 0; i < 100; i++) {
button[i] = new JButton();
button[i].setBackground(Color.BLUE);
comppanel.add(button[i]);
//changing colour of buttons when clicked
button[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
Object source = ev.getSource();
if (source instanceof Component) {
((Component) source).setBackground(Color.GREEN);
}
}
});
}
//creating menu panel
JPanel menupanel = new JPanel();
//creating buttons for menu
JButton save = new JButton("Save");
JButton load = new JButton("Load");
save.setPreferredSize(new Dimension(100, 100));
load.setPreferredSize(new Dimension(100, 100));
//adding buttons to menu panel
menupanel.add(save);
menupanel.add(load);
//adding panels into frame
frame.add(userpanel, BorderLayout.WEST);
frame.add(menupanel, BorderLayout.CENTER);
frame.add(comppanel, BorderLayout.EAST);
frame.setVisible(true);
frame.setSize(2000, 1000);
}
}
As I say, it works perfectly on my Windows Eclipse but not on Mac

Changing background color of a ContentPane

I'm working on a GUI and I'm not having some trouble with panes.
My GUI is divided into two parts (topPane and bottomPane).
I have buttons and labels on both panes, but one of the button functions I wanted to change the background color, but it's not doing the job.
What I did is that I used a Container (called thisContentPane) to change the background color of my entire GUI.
Here is my current code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TempConverter extends JFrame
{
//Creating a contentPane down inside the inner class
Container thisContentPane;
//class scope variables : DO NOT CREATE THIS OBJECTS HERE.
JButton calculateButton, clearButton;
JTextField celsiusField, fahrenheitField, kelvinField;
//menu
JMenuBar menuBar = new JMenuBar();
JMenu backgroundColor = new JMenu("Background Color");
JMenu help = new JMenu("Help");
JMenuItem lightGray, white, black, blue, howToUse, about;
//constructor
TempConverter()
{
super("Temperature Converter App");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.setSize(400,200);;
this.setLocationRelativeTo(null);
//menuBar
this.setJMenuBar(menuBar);
menuBar.add(backgroundColor);
//adding JMenu to JMenuBar
menuBar.add(backgroundColor);
menuBar.add(help);
//adding JMenuItems
lightGray = backgroundColor.add("LIGHTGRAY");
white = backgroundColor.add("WHITE");
black = backgroundColor.add("BLACK");
blue = backgroundColor.add("BLUE");
howToUse = help.add("How To Use");
about = help.add("Help");
//babysitter
MaryPoppins babysitter = new MaryPoppins();
//adding action listener to the menu item
lightGray.addActionListener(babysitter);
white.addActionListener(babysitter);
black.addActionListener(babysitter);
blue.addActionListener(babysitter);
howToUse.addActionListener(babysitter);
about.addActionListener(babysitter);
//building JPanels
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(3,2,0,20));
//add this to JFrame in centerzone
this.add(topPanel, BorderLayout.CENTER);
//bottom panel
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout());
//add this to JFrame in bottom
this.add(bottomPanel, BorderLayout.SOUTH);
//add components to the panels
//add the buttons
calculateButton = new JButton("Calculate");
clearButton = new JButton("Clear");
//add buttons
bottomPanel.add(calculateButton);
bottomPanel.add(clearButton);
//register listeners
calculateButton.addActionListener(babysitter);
clearButton.addActionListener(babysitter);
//add components to the top panel
JLabel labelOne = new JLabel("Celsius:");
JLabel secondOne = new JLabel("Fahrenheit:");
JLabel thirdOne = new JLabel("Kelvin:");
celsiusField = new JTextField("");
fahrenheitField = new JTextField("");
kelvinField = new JTextField("");
//add the label and text fields
topPanel.add(labelOne);
topPanel.add(celsiusField);
topPanel.add(secondOne);
topPanel.add(fahrenheitField);
topPanel.add(thirdOne);
topPanel.add(kelvinField);
this.setVisible(true);
} // end constructor
public static void main (String[] args) {
new TempConverter();
}
private class MaryPoppins implements ActionListener
{
//implement the abstract method from the interface
public void actionPerformed(ActionEvent ev)
{
thisContentPane = getContentPane();
if(ev.getActionCommand().equals("LIGHTGRAY"))
{
thisContentPane.setBackground(Color.lightGray);
}
else if (ev.getActionCommand().equals("BLUE"))
{
thisContentPane.setBackground(Color.BLUE);
}
else if(ev.getActionCommand().equals("WHITE") )
{
thisContentPane.setBackground(Color.WHITE);
}
else if (ev.getActionCommand().equals("BLACK"))
{
thisContentPane.setBackground(Color.BLACK);
}else if (ev.getActionCommand().equals("Clear"))
{
thisContentPane.setBackground(Color.BLACK);
}
else if (ev.getActionCommand().equals("BLACK"))
{
thisContentPane.setBackground(Color.BLACK);
}
}//end ActionPerformed()
}//end inner class
} // end class
When I click the buttons or menu items it doesn't do anything.
Your problem is that your contentPanel's background color is not "visible": your topPanel and your bottomPanel are on top of it :)
You should either do:
if (ev.getActionCommand().equals("LIGHTGRAY")) {
thisTopPanel.setBackground(Color.lightGray);
thisBottemPanel.setBackground(Color.lightGray);
}
... and do it for each of your if conditions (you know what I mean).
But that's not really the best way to go. An alternative that, in my opinion, makes perfect sense 'cause it reflects the exact behaviour you're looking for, would be:
topPanel.setOpaque(false);
bottomPanel.setOpaque(false);
I would obviously recommend the second option ;)
Also, since I'm at it, I prefer to use Color.LIGHTGRAY (and Color.BLACK, Color.WHITE, etc.) instead of Color.lightGrey, because these aliases respect the convention that states that constants must be upper-case.

Calling a JPanel inside a split panel Java

Hi I'm having trouble in my code. I can't call or display my JPanel(TruthTable) inside my splitpane in the Minimize class when I click the button and Keypressed(Enter).The problem is in the class Minimize
*UPDATE: I'have solved my problem regarding to diplaying the panel my next problem is when I call the constructor the text in the panel should be updated.I also change the setText to append 'coz they say that JPanel doesnt support setText.I've already used,validate,repaint method but no luck in updating the textArea.
Heres my code for class Minimize:
package splashdemo;
public class Minimize extends JPanel implements ClipboardOwner
{
simButton.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent ae)
{
LogicGates lg= new LogicGates();
lg.geth();
sim s=new sim();
s.InputExp(lg.g,lg.g1);
s.menu();
s.setSize(700,700);
s.setVisible(false);
Frame f = new Frame();
Panel panel = new Panel();
f.add(BorderLayout.SOUTH, panel);
f.add(BorderLayout.CENTER, new sim());
f.add(BorderLayout.SOUTH, panel);
f.setSize(580, 500);
panel.add(s.button);
f.show();
f.setVisible(false);
JOptionPane.showMessageDialog(null, b);
ex=b;
cAppend();
JOptionPane.showMessageDialog(null, ex1);
InToPost(ex1);
foutput= doTrans();
JOptionPane.showMessageDialog(null, foutput);
TruthTable_1 kl = new TruthTable_1(foutput);
Minimize mi = new Minimize();
s.InputExp(lg.g,lg.g1);
s.menu();
lg.gatessplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mi, lg.p1);
//here's the splitpane where I should display the TruthTable_1 panel but it doesn't diplay
lg.p1.add(lg.gatessplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, s,kl));
lg.gatessplit.setOneTouchExpandable(true);
lg.gatessplit.setDividerLocation(250);
lg.gatessplit.setPreferredSize(new Dimension(900, 500));
lg.createAndShowGUI();
}});
}
Heres my code the TruthTable_1:constructors
public TruthTable_1() {
super();
tableArea.append("This is a Test");
//setBackground(Color.black);
createg();
setVisible(true);
}
public void createg(){
setLayout(new BorderLayout());
line= 0;
truth= 'T';
fallacy= 'F';
final JPanel top= new JPanel();
input= new TextField(35);
TFCheck= new Checkbox("Select for \"1/0\" (default\"T/F\")");
check= new JButton("Check");
check.addActionListener(this);
top.add(input);
top.add(TFCheck);
top.add(check);
top.setVisible(false);
tableArea= new JTextArea(16, 40);
tableArea.setEditable(false);
tableArea.setFont(new Font("Lucida Console", Font.PLAIN, 14));
// all letters are the same width in this font
go= new JButton("Do it to it!");
go.addActionListener(this);
input.addActionListener(this);
go.setVisible(false);
add(top, BorderLayout.NORTH);
scrolls= new JScrollPane(tableArea);// add scroll buttons to the area
add(scrolls, BorderLayout.CENTER);
add(go, BorderLayout.SOUTH);
setSize(535, 500);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(100, 100);
}
public TruthTable_1(String f){
createg();
tableArea.append(run(f));
}

Categories

Resources