JTabbedPane with button getting the pane - java

I have a JTappedPane with a button on that I want to make close that tab.
I am doing it like so:
jTabbedPane1.addTab(title, null, panel, null);
JPanel pnl = new JPanel();
JButton close = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("x.png"));
close.setIcon(new ImageIcon(img));
} catch (IOException ex) {
ex.printStackTrace();
}
close.setPreferredSize(new Dimension(10, 10));
close.setBorderPainted(false);
close.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(ActionEvent evt) {
//TODO CLOSE THE TAP WHEN BUTTON IS PRESSED
}
}});
JLabel lab = new JLabel(s);
pnl.setOpaque(false);
pnl.add(lab);
pnl.add(close);
jTabbedPane1.setTabComponentAt(jTabbedPane1.getTabCount() - 1, pnl);
I am trying to get the title of the tab on the tab that the button has been pressed on.
I thought i could do something like
close.getContaining() to return the tab it is on but I was wrong.
Any Ideas?

If I understand you correctly, you want to find the index of the tab which has the parent of the button as tabComponent:
public void actionPerformed(ActionEvent evt) {
JComponent source = (JComponent) evt.getSource();
Container tabComponent = source.getParent();
int tabIndex = jTabbedPane1.indexOfTabComponent(tabComponent);
jTabbedPane1.removeTabAt(tabIndex);
}

You could simply write:
jTabbedPane1.removeTabAt(jTabbedPane1.getSelectedIndex());

Related

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

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

JButton requires two clicks after getting enabled in JAVA

I am trying to build a JFrame with four manual input JTextFields: description, hours, minutes, ID
and two JButtons: Submit and Reset
I need to disable the "Submit" button until all text fields have some data. To achieve this, I have used the DocumentListener and that is working fine, that is, initially the "Submit" button is disabled and gets enabled only when all text fields have some input.
PROBLEM: After "Submit" button is enabled, I need to hit the submit button twice to get the actual action trigger (probably first time is to restore focus after getting enabled, second time to do actual work). This issue does not happen with the "Reset" button.
TRIED AND DIDN'T WORK: I tried restoring focus using submit.requestFocusInWindow() and it brought focus to the "Submit" button but the last modified text field lost focus and I had to click it again to restore focus on that field.
Please assist. I am quite new to StackOverflow, so kindly don't close the thread.
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel titlePanel = new JPanel();
JPanel descPanel = new JPanel();
JPanel timeWorkedPanel = new JPanel();
JPanel iDPanel = new JPanel();
titlePanel.add(title);
mainPanel.add(titlePanel);
descPanel.add(desc);
mainPanel.add(descPanel);
timeWorkedPanel.add(hour);
timeWorkedPanel.add(minute);
mainPanel.add(timeWorkedPanel);
iDPanel.add(iD);
mainPanel.add(iDPanel);
JTextArea reqList = new JTextArea();
reqList.setLineWrap(false);
reqList.setEditable(false);
JScrollPane reqListScroll = new JScrollPane (reqList);
reqListScroll.setPreferredSize(new Dimension(400,400));
reqListScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
reqListScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
reqListScroll.setColumnHeaderView(new JLabel(" REQUEST CREATED TIME WORKED"));
mainPanel.add(reqListScroll);
List<JTextField> textFieldList = new ArrayList<>();
textFieldList.add(desc);
textFieldList.add(hour);
textFieldList.add(minute);
textFieldList.add(csiID);
JButton submit = new JButton("SUBMIT");
JButton reset = new JButton("RESET");
buttonPanel.add(submit);
buttonPanel.add(reset);
mainPanel.add(buttonPanel);
mainPanel.add(Box.createVerticalStrut(20)); // a spacer
JFrame mainFrame = new JFrame("Test Frame");
mainFrame.getContentPane().add(mainPanel);
mainFrame.setSize(new Dimension(500,600));
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
submit.setEnabled(false);
DocumentListener docListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
boolean isEnabled = true;
for(JTextField tf : textFieldList) {
if(tf.getText().isEmpty())
isEnabled = false;
}
submit.setEnabled(isEnabled);
}
};
for(JTextField tf : textFieldList) {
tf.getDocument().addDocumentListener(docListener);
}
final WebDriver newDriver = driver;
final ChromeOptions newOptions = options;
//Click on "SUBMIT" button
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
System.out.println("submitting");
mainFrame.setVisible(false);
createTicket(newDriver, newOptions, subportfolio, title, desc , hour, minute, csiID);
mainFrame.setVisible(true);
} catch (InterruptedException e1) {
}
}
});
//Click on "RESET" button
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
desc.setText(null);
hour.setText(null);
minute.setText(null);
csiID.setText(null);
}
});

Catch Jbutton pressed not by label

I would catch by a listener the button pressed but not by the text inside it because I've button only with background image.
This code catch it by label inserted in the jbutton constructor but I don't want show this label.
So or I find a way to hide label on button or I don't insert a label and catch button by some other handle.
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JButton b = (JButton)e.getSource();
JOptionPane.showMessageDialog(null,"È stato premuto"+b.getActionCommand());
}
}
Use setActionCommand() to avoid a default action command of the button text.
JButton myButton = new JButton();
myButton.setActionCommand("myButtonCommand");
public void actionPerformed(ActionEvent ae) {
String actionCommand = ae.getActionCommand();
if (actionCommand.equals("myButtonCommand")) {
// do something...
}
}
ImageIcon ic=new ImageIcon("C:/image.png");
JButton btn=new JButton(ic);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JButton b = (JButton)ae.getSource();
JOptionPane.showMessageDialog(null,"È stato premuto"+b.getActionCommand());
}
});

JButtons not displaying until mouse hover

I'm creating a gui that has 2 panels. When the gui is first loaded only one panel is visible and when a button is pressed the new panel is displayed. The problem is that on the 2nd panel when it loads the buttons are invisible and only display when the mouse hovers over them. On top of that when you move the screen they become invisible again and need to be hovered over to be displayed again.
I really don't know what to try as I have looked at methods of having multiple panels and this seems the best way to do it and aswell as this the buttons are implmented the same way I have implemented them for the 1st panel and they render correctly.
Full Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui {
private JFrame frame;
private JPanel panel1;
private JPanel panel2;
private JButton btnShip1, btnShip2, btnShip3, btnTutorial, btnLeftControl, btnHull, btnTargeting, btnRadar, btnWarning, btnRightControl;
private JTextField txtCharacterName, txtShipName;
private JLabel welcome, background;
public static void main(String[] args) {
new Gui();
}
public Gui(){
createWindow();
addButtons();
addFields();
addWelcome();
frame.add(panel1);
frame.setVisible(true);
addBackground();
addShipControls();
}
public void createWindow(){
frame = new JFrame();
frame.setTitle("Space Battle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(642, 518);
panel1 = new JPanel();
panel1.setLayout(null);
panel1.setBackground(Color.decode("#242627"));
panel2 = new JPanel();
panel2.setLayout(null);
panel2.setBackground(Color.decode("#242627"));
}
public void addButtons(){
btnShip1 = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/cruiserSelectBtn.jpg");
btnShip1.setIcon(img);
}
catch (Exception e) {}
try
{
ImageIcon img = new ImageIcon ("resources/button_1_hover.gif");
btnShip1.setRolloverIcon(img);
}
catch (Exception e) {}
btnShip1.setBounds(246,0,380,160);
btnShip1.setMargin(new Insets(0, 0, 0, 0));
btnShip1.addActionListener(new cruiserSelectHandler());
btnShip1.setBorder(null);
panel1.add (btnShip1);
btnShip2 = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/fighterSelectBtn.jpg");
btnShip2.setIcon(img);
}
catch (Exception e) {}
try
{
ImageIcon img = new ImageIcon ("resources/button_2_hover.gif");
btnShip2.setRolloverIcon(img);
}
catch (Exception e) {}
btnShip2.setBounds(246,160,380,160);
btnShip2.setMargin(new Insets(0, 0, 0, 0));
btnShip2.addActionListener(new fighterSelectHandler());
btnShip2.setBorder(null);
panel1.add (btnShip2);
btnShip3 = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/battleSelectBtn.jpg");
btnShip3.setIcon(img);
}
catch (Exception e) {}
try
{
ImageIcon img = new ImageIcon ("resources/button_3_hover.gif");
btnShip3.setRolloverIcon(img);
}
catch (Exception e) {}
btnShip3.setBounds(246,320,380,160);
btnShip3.setMargin(new Insets(0, 0, 0, 0));
btnShip3.addActionListener(new battleSelectHandler());
btnShip3.setBorder(null);
panel1.add (btnShip3);
btnTutorial = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/tutorialBtn.jpg");
btnTutorial.setIcon(img);
}
catch (Exception e) {}
btnTutorial.setBounds(5,426,234,49);
btnTutorial.setMargin(new Insets(0, 0, 0, 0));
panel1.add (btnTutorial);
}
public void addFields(){
txtCharacterName = new JTextField("Insert Character Name");
txtCharacterName.setBounds(12,260,220,35);
panel1.add(txtCharacterName);
txtShipName = new JTextField("Insert Ship Name");
txtShipName.setBounds(12,315,220,35);
panel1.add(txtShipName);
}
public void addWelcome(){
welcome = new JLabel ();
try
{
ImageIcon img = new ImageIcon ("resources/welcome.jpg");
welcome.setIcon(img);
}
catch (Exception e) {}
welcome.setBounds(0,0,247,229);
panel1.add(welcome);
}
//Class used to change panels
class cruiserSelectHandler implements ActionListener {
public void actionPerformed(ActionEvent even) {
frame.add(panel2);
panel1.setVisible(false);
}
}
class fighterSelectHandler implements ActionListener {
public void actionPerformed(ActionEvent even) {
frame.add(panel2);
panel1.setVisible(false);
}
}
class battleSelectHandler implements ActionListener {
public void actionPerformed(ActionEvent even) {
frame.add(panel2);
panel1.setVisible(false);
}
}
public void addBackground(){
//Is the background interfering?
background = new JLabel ();
try
{
ImageIcon img = new ImageIcon ("resources/background.jpg");
background.setIcon(img);
}
catch (Exception e) {}
background.setBounds(0,0,640,480);
panel2.add(background);
}
//Class used to add controls/buttons
public void addShipControls(){
btnLeftControl = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/left_controls.png");
btnLeftControl.setIcon(img);
}
catch (Exception e) {}
btnLeftControl.setBounds(-8,319,131,160);
btnLeftControl.setMargin(new Insets(0, 0, 0, 0));
btnLeftControl.setBorder(null);
panel2.add (btnLeftControl);
btnHull = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/hull_controls.png");
btnHull.setIcon(img);
}
catch (Exception e) {}
btnHull.setBounds(123,319,91,160);
btnHull.setMargin(new Insets(0, 0, 0, 0));
btnHull.setBorder(null);
panel2.add (btnHull);
btnTargeting = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/targeting_controls.png");
btnTargeting.setIcon(img);
}
catch (Exception e) {}
btnTargeting.setBounds(214,319,202,160);
btnTargeting.setMargin(new Insets(0, 0, 0, 0));
btnTargeting.setBorder(null);
panel2.add (btnTargeting);
btnWarning = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/warning_controls.png");
btnWarning.setIcon(img);
}
catch (Exception e) {}
btnWarning.setBounds(416,411,86,68);
btnWarning.setMargin(new Insets(0, 0, 0, 0));
btnWarning.setBorder(null);
panel2.add (btnWarning);
btnRadar = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/radar_idea.gif");
btnRadar.setIcon(img);
}
catch (Exception e) {}
btnRadar.setBounds(416,319,86,92);
btnRadar.setMargin(new Insets(0, 0, 0, 0));
btnRadar.setBorder(null);
panel2.add (btnRadar);
btnRightControl = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/right_controls.png");
btnRightControl.setIcon(img);
}
catch (Exception e) {}
btnRightControl.setBounds(502,319,131,160);
btnRightControl.setMargin(new Insets(0, 0, 0, 0));
btnRightControl.setBorder(null);
panel2.add (btnRightControl);
}
}
when a button is pressed the new panel is displayed.
The problem is:
you are using a null layout
you are add two different panels to the frame.
By default Swing paints components in the reverse order that they were added.
So when you add panel1, it is the only panel of the frame so it is painted.
Then you click a button and add panel2. So Swing paints panel2 and then repaints panel1 on top, so panel2 is hidden. When you mouse over the button it appears because buttons listen for mouseEntered events and the button gets repainted.
When you resize the screen panel2 is painted and then panel1 is painted so you have the problem again.
The solution is to use a proper layout manager. In your case you should be using a Card Layout. The Card Layout will swap panels making sure only one panel is ever visible at a time. Read the Swing tutorial on Using Card Layout. Then get rid of all the null layouts and setBounds() methods.

JButton unresponsive to actionListener

I've trouble with actionListener. I created own simple dialog, which has only two JButtons - Yes and No. When I click on button, actionListener doesn't respond.
This is my code:
private void showInfoNewUML() {
Dimension buttonsSize = new Dimension(60, 25);
Dimension programSize = new Dimension(1200, 700);
final JDialog dialogWindow = new JDialog(this, "Erase actual UML diagram"
+ " with his files", true);
JTextArea descDialogWindow = new JTextArea("Do you really erase actual\n"
+ "UML diagram with his files? ");
descDialogWindow.setEditable(false);
descDialogWindow.setBackground(new Color(220, 220, 220));
descDialogWindow.setBorder(null);
dialogWindow.getContentPane().setBackground(new Color(220, 220, 220));
dialogWindow.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
dialogWindow.setModal(true);
dialogWindow.setResizable(false);
dialogWindow.setLayout(new FlowLayout());
dialogWindow.setSize(310, 100);
dialogWindow.setLocation((int) programSize.getWidth() / 2,
(int) programSize.getHeight() / 2);
JButton buttonYes = new JButton("Yes");
JButton buttonNo = new JButton("No");
buttonYes.setPreferredSize(buttonsSize);
buttonNo.setPreferredSize(buttonsSize);
dialogWindow.add(descDialogWindow);
dialogWindow.add(buttonYes);
dialogWindow.add(buttonNo);
dialogWindow.setVisible(true);
buttonYes.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonAnoActionPerformed(e);
}
private void buttonAnoActionPerformed(ActionEvent e) {
dialogWindow.setVisible(false);
}
});
buttonNo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonNeActionPerformed(e);
}
private void buttonNeActionPerformed(ActionEvent e) {
dialogWindow.setVisible(false);
}
});
}
I would like close this dialog after I click on button. When I click to top right button with cross, dialog window closes.
Thank you for help with this trouble.
Try adding the ActionListeners before calling dialogWindow.setVisible(true);.
Your dialog is modal, and so showInfoNewUML will block at dialogWindow.setVisible(true); until after the dialog is closed, which is too late to register any useful listeners.

Categories

Resources