Changing the size of a jFrame on button click - java

I'm creating a "Presentation" on a jFrame as part of a project and need some help.
I have it starting as a 200, 200 size frame with a button in the middle that says "Let's Start"
then when you click on it, the size of the frame changes. When I click on the button you have to drag the window to make it the already defined size seen as the window stays the original 200 by 200 it doesn't open the window to 1335 by 675.
Here's my code.
package randomGUIs;
import java.awt.Color;
import java.awt.Dimension;
public class Presentation extends javax.swing.JFrame {
public Presentation() {
initComponents();
startPanel.setBackground(Color.blue);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
startPanel = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Let's Start");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout startPanelLayout = new javax.swing.GroupLayout(startPanel);
startPanel.setLayout(startPanelLayout);
startPanelLayout.setHorizontalGroup(
startPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(startPanelLayout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jButton1)
.addContainerGap(49, Short.MAX_VALUE))
);
startPanelLayout.setVerticalGroup(
startPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(startPanelLayout.createSequentialGroup()
.addGap(78, 78, 78)
.addComponent(jButton1)
.addContainerGap(77, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(startPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(startPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
startPanel.setSize(new Dimension(1335, 675));
startPanel.setMaximumSize(new Dimension(1335, 675));
startPanel.setMinimumSize(new Dimension(1335, 675));
jButton1.setVisible(false);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Presentation().setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JPanel startPanel;
}
I've tried using startPanel.repaint(); with no luck.

Simply set the frame size with this function.
In order to use this function you must include the relevant package.
import java.awt.Dimension;
...
setSize(new Dimension(1320,220));

Your JFrame won't automagically resize itself unless you tell it to. Something like this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
startPanel.setSize(new Dimension(1335, 675));
startPanel.setMaximumSize(new Dimension(1335, 675));
startPanel.setMinimumSize(new Dimension(1335, 675));
frame.setSize(1335, 675);
jButton1.setVisible(false);
}
You could also use the pack() function of the JFrame class, depending on what you wanted to do.

Related

How to read Text Field value from another file through a Dialog?

I have two files in my package: GUI.java and Dialog.java
The GUI has two Text Fields and a Button. When I press that Button, the Dialog becomes visible. The Dialog has another button which saves the Text Fields' values to an .ini file. And here comes the problem, it doesn't save the updated values, but the ones that were there when the program first started.
After some searches on Google I found out that I need to use something called "Action Listener", but I just can't seem to get it right at all.
GUI.java:
import java.io.File;
import java.io.IOException;
import org.ini4j.Wini;
public class GUI extends javax.swing.JFrame {
public GUI(){
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
textField1 = new javax.swing.JTextField();
textField2 = new javax.swing.JTextField();
openDialog = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
textField1.setText("1");
textField2.setText("2");
openDialog.setText("Open Dialog");
openDialog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openDialogActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(openDialog, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(openDialog)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void openDialogActionPerformed(java.awt.event.ActionEvent evt) {
Dialog dialog = new Dialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
dialog.setVisible(false);
}
});
dialog.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new GUI().setVisible(true);
}
});
}
void save(int i){
try {
Wini ini = new Wini(new File("C:/Users/Paul/Desktop/Configs.ini"));
int firstValue = Integer.parseInt(textField1.getText());
int secondValue = Integer.parseInt(textField2.getText());
ini.put("Configuration " + i, "First Value", firstValue);
ini.put("Configuration " + i, "Second Value", secondValue);
ini.store();
}
catch (IOException ex) {}
}
private javax.swing.JButton openDialog;
private javax.swing.JTextField textField1;
private javax.swing.JTextField textField2;
}
Dialog.java:
public class Dialog extends javax.swing.JDialog {
GUI GUI = new GUI();
public Dialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
save = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
save.setText("Save");
save.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(save)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(save)
.addContainerGap())
);
pack();
}// </editor-fold>
private void saveActionPerformed(java.awt.event.ActionEvent evt) {
GUI.save(1);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Dialog dialog = new Dialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
private javax.swing.JButton save;
}
Dialog should not be creating a new instance of GUI, there is no relationship between the instance which is been displayed on the screen and that which Dialog is using.
Instead, GUI should pass a reference of itself to Dialog
public class Dialog extends javax.swing.JDialog {
private GUI gui;
public Dialog(GUI parent) {
super(parent, true);
this.gui = gui;
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
save = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
save.setText("Save");
save.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(save)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(save)
.addContainerGap())
);
pack();
}// </editor-fold>
private void saveActionPerformed(java.awt.event.ActionEvent evt) {
gui.save(1);
}
private javax.swing.JButton save;
}
This is pretty basic Java and something you should be familiar with before embarking on something as complicated as GUI development. See Passing Information to a Method or a Constructor for more details
And your GUI class might look something like...
public class GUI extends javax.swing.JFrame {
public GUI() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
textField1 = new javax.swing.JTextField();
textField2 = new javax.swing.JTextField();
openDialog = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
textField1.setText("1");
textField2.setText("2");
openDialog.setText("Open Dialog");
openDialog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openDialogActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(openDialog, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(openDialog)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void openDialogActionPerformed(java.awt.event.ActionEvent evt) {
Dialog dialog = new Dialog(this);
dialog.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new GUI().setVisible(true);
}
});
}
void save(int i) {
// Code I can't execute
// Also, don't ignore the exception, you should probably
// rethrow it...
}
private javax.swing.JButton openDialog;
private javax.swing.JTextField textField1;
private javax.swing.JTextField textField2;
}
Although, I'd argue that, if you want GUI to save the data, it should be inspecting the result from the dialog, rather the exposing itself to possible mis-treatment (removeAll anyone?). In that case, I'd consider using a JOptionPane instead
See How to Make Dialogs for more details.
Also, the sooner you ditch the form editor, the better you will become
I will look forward and see if I can manage to make it work through JOptionPane
private void openDialogActionPerformed(java.awt.event.ActionEvent evt) {
int response = JOptionPane.showOptionDialog(this, "Do you wish to save", "Save", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
if (response == JOptionPane.YES_OPTION) {
save(1);
}
}

Prevent JPopupMenu from being covered by task bar

How do I make my JPopupMenu appear above the task bar? In other words, how do I force it to honour screen limits so it doesn't get covered? Take Android Studio's pop up menu for example:
Normal position:
And when I drag the window near the bottom task bar, the pop up "adapts" and appears above it:
And now my test case:
Normal position:
Near the task bar (you can see how, unlike the Android Studio one, part of the pop up disappears under the task bar):
Code for the test case:
Test.java
public class Test extends javax.swing.JFrame {
public Test() {
initComponents();
}
public void initUI() {
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
btnMenu = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnMenu.setText("Click for Menu");
btnMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnMenuActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(291, Short.MAX_VALUE)
.addComponent(btnMenu)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(266, Short.MAX_VALUE)
.addComponent(btnMenu)
.addContainerGap())
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void btnMenuActionPerformed(java.awt.event.ActionEvent evt) {
JPopupMenu menu = new JPopupMenu();
menu.add(new PopBody());
menu.show(this, btnMenu.getLocation().x - 95, btnMenu.getLocation().y + 60);
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
}
java.awt.EventQueue.invokeLater(() -> new Test().setVisible(true));
}
// Variables declaration - do not modify
private javax.swing.JButton btnMenu;
// End of variables declaration
}
PopBody.java
public class PopBody extends javax.swing.JPanel {
public PopBody() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
lblBody = new javax.swing.JLabel();
btnOK = new javax.swing.JButton();
lblBody.setText("Panel body");
btnOK.setText("OK");
btnOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOKActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(77, 77, 77)
.addComponent(lblBody)
.addContainerGap(92, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnOK)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(73, 73, 73)
.addComponent(lblBody)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
.addComponent(btnOK)
.addContainerGap())
);
}// </editor-fold>
private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {
}
// Variables declaration - do not modify
private javax.swing.JButton btnOK;
private javax.swing.JLabel lblBody;
// End of variables declaration
}
I stumbled across this problem myself and came up with this solution.
private void btnMenuActionPerformed(ActionEvent evt) {
JPopupMenu popup = new JPopupMenu();
popup.add(new PopBody());
popup.pack();
int popUpHeight = popup.getPreferredSize().height;
//determines the max available size of the screen
Rectangle windowBounds = GraphicsEnvironment.
getLocalGraphicsEnvironment().getMaximumWindowBounds();
Point invokerPosition = ((Component)evt.getSource()).getLocationOnScreen();
if (invokerPosition.y + popUpHeight > windowBounds.height) {
//get the negative margin and use it as the y-offset
popup.show(this, 0, windowBounds.height - (invokerPosition.y + popUpHeight));
}
else {
popup.show(this, 0, 0);
}
}
I'm not sure about your hard-coded offsets though.

JInternalFrame Opening and Focus

I've got a couple JInternalFrames inside a DesktopPane, and I've noticed something with the first time they open.
When I first open one, and then open a second one, the first JInternalFrame will be on top of the second. I want them to open on top of each other, but this only happens the first time. I realize now that it is because of the order that they are added. But my program will be retrieving information right at the desktoppane load so I need the JIF variables to be added before the windows are actually opened. So how can I make sure the window that is opened comes out on top regardless of the order they are added?
I would prefer not to use a dialogbox.
Try this code...
I've create a sample application for you to understand...
public class NewJFrame extends javax.swing.JFrame {
private javax.swing.JButton jButton1;
private javax.swing.JDesktopPane jDesktopPane1;
//This is a Internal Frame I have created
private PaymentInternalFrame payIF;
public NewJFrame() {
initComponents();
}
private void initComponents() {
jButton1 = new javax.swing.JButton();
jDesktopPane1 = new javax.swing.JDesktopPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Click");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jDesktopPane1Layout = new javax.swing.GroupLayout(jDesktopPane1);
jDesktopPane1.setLayout(jDesktopPane1Layout);
jDesktopPane1Layout.setHorizontalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jDesktopPane1Layout.setVerticalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 412, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE)
.addComponent(jDesktopPane1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jDesktopPane1))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
if(payIF==null||payIF.isClosed()){
payIF = new PaymentInternalFrame();
mainDesktop.add(payIF);
payIF.setVisible(true);
payIF.setMaximum(true);
payIF.isSelected();
}else{
payIF.setSelected(true);
}
} catch (PropertyVetoException e) {
NotificationMessage.errorMessage(this, e);
}
}
//Main Method...
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
}

Can't draw to JPanel with getGraphics

I was wondering what went wrong. I've done this before but for some reason I can't get this to work this time.
I designed the project in Netbeans. The most relevant part is the method initTiras, which is suppossed to draw something, but it doesn't. I included the code generated by NetBeans.
Here's the most simplified version of the code, and still it paints nothing.
So I created a new Frame in the proyect. Then I put a JPanel in it (in desing mode). The JPanel's called ElPanel and the JFrame LaFrame.
Here's the main class:
package ElPackage;
public class Resistores {
public static void main(String[] args) {
LaFrame UnaFrame = new LaFrame();
UnaFrame.setVisible(true);
}
}
Inside the LaFrame class:
package ElPackage;
import java.awt.Color;
import java.awt.Graphics;
public class LaFrame extends javax.swing.JFrame {
public LaFrame () {
initComponents();
initTiras();
}
public void initTiras() {
Graphics LasG = ElPanel.getGraphics();
LasG.setColor(Color.WHITE);
LasG.fillRect(10, 10, 30, 30);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
ElPanel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
ElPanel.setBackground(new java.awt.Color(51, 0, 51));
ElPanel.setForeground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout ElPanelLayout = new javax.swing.GroupLayout(ElPanel);
ElPanel.setLayout(ElPanelLayout);
ElPanelLayout.setHorizontalGroup(
ElPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
ElPanelLayout.setVerticalGroup(
ElPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ElPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ElPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JPanel ElPanel;
// End of variables declaration
}
Override paintComponent(Graphics g) method of elPanel and add your code there. See for example
Use java naming convention - variables should start from lowercase letter.

JAVA Swing - tabbed panel setSelectedIndex() on a card panel from another card panel

I have a GUI as shown below. the tabbed pane in the card layout card 1 panel show 1st tab by default. When i navigate to card 2, I would like to know how to make the button there to navigate to card 1 tab 3. I know how to get to card 1 from that button by using getParent(), but I don't know how to show a specific tab I want from there. (Note: card 1 and card 2 are two different JPanel classes, the parent is a JFrame class)
Image: Left side as card 1 with tabbed panel , Right side as card 2
The following is my code:
the main JFrame:
import java.awt.CardLayout;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jbtCard1 = new javax.swing.JButton();
jbtCard2 = new javax.swing.JButton();
cardPane = new javax.swing.JPanel();
jPanelCard11 = new CardLayoutTest.JPanelCard1();
jPanelCard21 = new CardLayoutTest.JPanelCard2();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jbtCard1.setText("Card 1");
jbtCard1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtCard1ActionPerformed(evt);
}
});
jbtCard2.setText("Card 2");
jbtCard2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtCard2ActionPerformed(evt);
}
});
cardPane.setName(""); // NOI18N
cardPane.setLayout(new java.awt.CardLayout());
cardPane.add(jPanelCard11, "card1");
cardPane.add(jPanelCard21, "card2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(87, 87, 87)
.addComponent(jbtCard1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jbtCard2)
.addGap(80, 80, 80))
.addComponent(cardPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(cardPane, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jbtCard2)
.addComponent(jbtCard1))
.addContainerGap())
);
pack();
}// </editor-fold>
private void jbtCard1ActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout card = (CardLayout) cardPane.getLayout();
card.show(cardPane, "card1");
}
private void jbtCard2ActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout card = (CardLayout) cardPane.getLayout();
card.show(cardPane, "card2");
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel cardPane;
private CardLayoutTest.JPanelCard1 jPanelCard11;
private CardLayoutTest.JPanelCard2 jPanelCard21;
private javax.swing.JButton jbtCard1;
private javax.swing.JButton jbtCard2;
// End of variables declaration
}
Card 1 Panel:
public class JPanelCard1 extends javax.swing.JPanel {
public JPanelCard1() {
initComponents();
}
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel2.setText("card 1 tab 1 ");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(101, 101, 101)
.addComponent(jLabel2)
.addContainerGap(233, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(62, 62, 62)
.addComponent(jLabel2)
.addContainerGap(138, Short.MAX_VALUE))
);
jTabbedPane1.addTab("tab1", jPanel1);
jLabel1.setText("card 1 tab 2");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(73, 73, 73)
.addComponent(jLabel1)
.addContainerGap(264, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jLabel1)
.addContainerGap(108, Short.MAX_VALUE))
);
jTabbedPane1.addTab("tab2", jPanel2);
jLabel3.setText("card 1 tab 3");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(140, 140, 140)
.addComponent(jLabel3)
.addContainerGap(197, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(jLabel3)
.addContainerGap(129, Short.MAX_VALUE))
);
jTabbedPane1.addTab("tab3", jPanel3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 58, Short.MAX_VALUE))
);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration
}
Card 2 Panel:
import java.awt.CardLayout;
import javax.swing.JPanel;
public class JPanelCard2 extends javax.swing.JPanel {
public JPanelCard2() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jButton1.setText("go to Card 1 tab 3");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setText("Card 2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(261, 261, 261)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addComponent(jLabel1)))
.addContainerGap(18, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(48, 48, 48)
.addComponent(jLabel1)
.addGap(75, 75, 75)
.addComponent(jButton1)
.addContainerGap(140, Short.MAX_VALUE))
);
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//show card 1 from here
CardLayout card = (CardLayout) this.getParent().getLayout();
card.show((JPanel) this.getParent(), "card1");
//card1 shown, but how to show specific tab in the tab pane from here?
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
I think you're looking for JTabbedPane.html.setSelectedIndex(int).
The following isn't the most elegant solution, but it should work without requiring a lot of refactoring.
Add a method in NewJFrame:
public CardLayoutTest.JPanelCard1 getJPanelCard11() {
return jPanelCard11;
}
Add a method in JPanelCard1:
public void setTab(int index) {
jTabbedPane1.setSelectedIndex(index);
}
Call these in JPanelCard2:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//show card 1 from here
CardLayout card = (CardLayout) this.getParent().getLayout();
card.show((JPanel) this.getParent(), "card1");
//card1 shown, show specific tab in the tab pane from here:
NewJFrame parent = (NewJFrame) this.getParent();
((JPanelCard1) parent.getJPanelCard11()).setTab(1);
}

Categories

Resources