JSlider problems with ticks - java

I'm trying to use JSlider for the first time and I tried consulting How to Use Sliders to learn the basics.
But when I try to make the ticks appear like this:
sliderInterior = new JSlider(JSlider.HORIZONTAL,-100,100,0);
sliderInterior.setMinorTickSpacing(5);
sliderInterior.setMajorTickSpacing(10);
sliderInterior.setPaintTicks(true);
The ticks just don't appear. What's the problem?
EDIT
Did a SSCCE as requested. The problem remains, a JSlider with no ticks at all.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Interface;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
public class JSliderTicks extends javax.swing.JDialog {
public JSliderTicks(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
slider = new JSlider(JSlider.HORIZONTAL,0,10,5);
slider.setMinorTickSpacing(1);
slider.setMajorTickSpacing(2);
slider.setPaintTicks(true);
JOptionPane.showMessageDialog(null, slider);
setVisible(true);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
slider = new javax.swing.JSlider();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(85, 85, 85)
.addComponent(slider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(115, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(117, 117, 117)
.addComponent(slider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(160, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
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(JSliderTicks.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JSliderTicks.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JSliderTicks.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JSliderTicks.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JSliderTicks dialog = new JSliderTicks(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);
}
});
}
// Variables declaration - do not modify
private javax.swing.JSlider slider;
// End of variables declaration
}
I only changed the constructor since I'm using JDialog Form and the rest is implemented automatically.
I just noticed, if I use JOptionPane the JSlider works fine but in the JDialog it stays unaltered.

It works just fine in this SSCCE.
import java.awt.*;
import javax.swing.*;
class SliderTicks {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JSlider sliderInterior = new JSlider(JSlider.HORIZONTAL, -100, 100, 0);
sliderInterior.setMinorTickSpacing(5);
sliderInterior.setMajorTickSpacing(10);
sliderInterior.setPaintTicks(true);
JOptionPane.showMessageDialog(null, sliderInterior);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}

What is happening is that you're creating an new JSlider in the consructor, when one is already create in the initComponents and added. Also, the JOptionPane, messes it up also, as a component can only be added to one parent container. I removed the JOptionPane and re-initialization of the JSlider and it works. I also set the minimum, maximum, and value accordingly.
initComponents();
//slider = new JSlider(JSlider.HORIZONTAL,0,10,5);
slider.setMinimum(0);
slider.setMaximum(10);
slider.setValue(5);
slider.setMinorTickSpacing(1);
slider.setMajorTickSpacing(2);
slider.setPaintTicks(true);
//JOptionPane.showMessageDialog(null, slider);
//setVisible(true); <<---- already set visible

Related

Adding a custom Swing component in a JFrame

I've created a simple JTextField (this will have a mask after and I'll use this in multiple projects) and I'm trying to add in a simple JFrame, however, when I run the code, doesn't appear on the frame.
Here's the code for the new frame:
public class TestFrame extends javax.swing.JFrame {
public TestFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
textFieldCPF1 = new org.japo.java.swing.samples.TextFieldCPF();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(196, 196, 196)
.addComponent(textFieldCPF1, javax.swing.GroupLayout.PREFERRED_SIZE, 386, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(214, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(101, Short.MAX_VALUE)
.addComponent(textFieldCPF1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(99, 99, 99))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
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(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private org.japo.java.swing.samples.TextFieldCPF textFieldCPF1;
// End of variables declaration
}
And here's the code for the JTextField:
package org.japo.java.swing.samples;
import java.text.ParseException;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;
/**
*
* #author ambro
*/
public class TextFieldCPF extends JFormattedTextField {
JFormattedTextField CPF = new JFormattedTextField();
public TextFieldCPF() throws ParseException {
CPF = new JFormattedTextField(new MaskFormatter("#########"));
}
public JFormattedTextField getCPF() {
return CPF;
}
public void setCPF(JFormattedTextField CPF) {
this.CPF = CPF;
}
}
And here there a screenshot of how it is on my IDE:
IDE
And this is when I run the code:
Running
Here is the Tutorial I was following: Tutorial1 and mostly this one

Having trouble moving a jButton

I'm trying to use Matisse in NetBeans to create a simple game...like Myst. I just want it to display a Frame that has things like a text field and buttons/inventory on the right. I can do that. Then I created a Jpanel that displays on the Frame. I've input some pictures and created a set of cards to make visible and invisible when needed. Each card/scene needs to have buttons that will be different for each scene. Basically I want to make transparent buttons for the user to press that do things (i.e. move to next picture/scene, find a key, etc...). I can create different buttons in each picture, but I can't seem to move them anywhere. I have a suspicion it's due to Matisse, but I don't know.
Here is some of the code, I'm sure it's crude as it's my first implementation of anything in Java. At the very bottom in the Scene to display I've added a button, that displays. I pretty much know now that the setBounds won't work due to the way position works...how would I then place it somewhere. Right now it just displays at the top mid of the picture.
SceneFrame:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package main;
import scene.SecondPanel;
import scene.FirstPanel;
import scene.Scene;
import javax.swing.JButton;
public class SceneFrame extends javax.swing.JFrame {
private FirstPanel sceneP;
private SecondPanel sceneSP;
/**
* Creates new form SceneFrame
*/
public SceneFrame() {
initComponents();
addCards();
}
public void addCards() {
sceneP = new FirstPanel();
SceneManager.add("SecondPanel", sceneP);
sceneSP = new SecondPanel();
SceneManager.add("FirstPanel", sceneSP);
sceneP.setVisible(false);
}
/**
* 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() {
SceneManager = new scene.ScenePanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout SceneManagerLayout = new javax.swing.GroupLayout(SceneManager);
SceneManager.setLayout(SceneManagerLayout);
SceneManagerLayout.setHorizontalGroup(
SceneManagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 517, Short.MAX_VALUE)
);
SceneManagerLayout.setVerticalGroup(
SceneManagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 421, Short.MAX_VALUE)
);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("jButton2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(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()
.addComponent(SceneManager, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(139, 139, 139)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(SceneManager, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 97, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
sceneP.setVisible(false);
//SceneManager.showScene("SecondPanel");
sceneSP.setVisible(true);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
sceneSP.setVisible(false);
//SceneManager.showScene("FirstPanel");
sceneP.setVisible(true);
}
/**
* #param args the command line arguments
*/
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(SceneFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SceneFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SceneFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SceneFrame.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 SceneFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel SceneManager;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
// End of variables declaration
}
Scene:
package scene;
import java.awt.Color;
import javax.swing.JPanel;
import java.awt.Image;
import javax.swing.ImageIcon;
public abstract class Scene extends JPanel {
public Image image;
private String sceneName;
public Scene(String cn) {
setName(cn);
this.setSize(600, 600);
this.setBackground(Color.WHITE);
}
public String getCardName() {
return sceneName;
}
public abstract void addControlButtons();
// public abstract void implementControlButtons();
}
A Panel to display:
/**
* Creates a new ForestScene Object.
*/
public SecondPanel() {
super("SecondPanel");
JButton Button2 = new JButton("SwagCity");
try {
image = (new ImageIcon(getClass().getResource("/resources/ForestPath.jpg"))).getImage();
} catch (Exception e) {/*How to handle?*/
}
this.addControlButtons();
}
#Override
public void addControlButtons(){
JButton bButton = new JButton("bButton");
//bButton.setBounds(200, 300, 500, 600); //How to display where I want?
bButton.setAlignmentX(1000);
this.add(bButton);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Graphics2D g2 = (Graphics2D) g;
if (image != null) {
boolean val = g.drawImage(image, 0, 0, 800, 600, this);
} else {
System.out.println("Image not found");
}
}
}
You need to add JFrame.frame.setLayout(null) so that you can adjust your fields(button,textfields) on to the frame.I too had a similar problem
I've figured out that it must be the layoutManager confusing something. If i set: this.setLayout(null); I can then set the bounds of the button and it displays where and how I want. I apologize if the question did not have enough information, but I did not know myself anymore than I told you. If anyone has anything to add about what I did, I'll be glad to select that as my answer.

JPanel not showing anything

I have a problem with JComponent's inside a JPanel that are not showing up.
I am using Netbeans' Java GUI Builder partially to build the GUI.
I got a MainFrame class which is build with the GUI Builder to take care of menu items.
I got a MainPanel class which is inside the MainFrame class (under the menu bar).
And then I manually add another JPanel to that MainPanel such that I can have full control of the GUI again without Netbeans GUI bothering me.
However when I add a JButton to that JPanel then nothing is showing up.
MainFrame.java (including Netbeans code):
package gui;
import javax.swing.JFrame;
/**
*
* #author Frank
*/
public class MainFrame extends javax.swing.JFrame {
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
customInit();
}
private void customInit() {
this.setTitle("Trading Card Game");
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
mainPanel1 = new gui.MainPanel();
jMenuBar1 = new javax.swing.JMenuBar();
menuFile = new javax.swing.JMenu();
menuFileQuit = new javax.swing.JMenuItem();
menuPreview = new javax.swing.JMenu();
menuPreviewStart = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout mainPanel1Layout = new javax.swing.GroupLayout(mainPanel1);
mainPanel1.setLayout(mainPanel1Layout);
mainPanel1Layout.setHorizontalGroup(
mainPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
mainPanel1Layout.setVerticalGroup(
mainPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
menuFile.setText("File");
menuFileQuit.setText("Quit");
menuFileQuit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuFileQuitActionPerformed(evt);
}
});
menuFile.add(menuFileQuit);
jMenuBar1.add(menuFile);
menuPreview.setText("Preview");
menuPreviewStart.setText("Start");
menuPreview.add(menuPreviewStart);
jMenuBar1.add(menuPreview);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void menuFileQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuFileQuitActionPerformed
System.exit(0);
}//GEN-LAST:event_menuFileQuitActionPerformed
/**
* #param args the command line arguments
*/
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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuBar jMenuBar1;
private gui.MainPanel mainPanel1;
private javax.swing.JMenu menuFile;
private javax.swing.JMenuItem menuFileQuit;
private javax.swing.JMenu menuPreview;
private javax.swing.JMenuItem menuPreviewStart;
// End of variables declaration//GEN-END:variables
}
MainPanel.java (including Netbeans code):
package gui;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import model.Game;
/**
*
* #author Frank
*/
public class MainPanel extends javax.swing.JPanel {
/**
* Creates new form MainPanel
*/
public MainPanel() {
initComponents();
initPanel();
}
private void initPanel() {
this.setBorder(BorderFactory.createLineBorder(Color.yellow));
this.add(new JButton("Test"), BorderLayout.CENTER);
revalidate();
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
setLayout(new java.awt.BorderLayout());
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
The yellow border is showing up around the JPanel though.
Any clue why the JButton with "Test" is not showing up?
Image describing the situation (look no button!):
Regards.
It is because you are overwriting your layout for mainPanel1.
I commented out these lines in MainFrame.java and the test button showed as expected.
// javax.swing.GroupLayout mainPanel1Layout = new javax.swing.GroupLayout(mainPanel1);
// mainPanel1.setLayout(mainPanel1Layout);
// mainPanel1Layout.setHorizontalGroup(
// mainPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
// .addGap(0, 400, Short.MAX_VALUE)
// );
// mainPanel1Layout.setVerticalGroup(
// mainPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
// .addGap(0, 279, Short.MAX_VALUE)
// );

Displaying dynamic components when building from IDE : Java

When I write a code for displaying a textfield,label etc. on an event say button click its works fine if I write the whole code and does not work if I drag-drop any components from netbeans.
How do I solve this problem ?
(Updated with codes)
Netbeans code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package maual;
import javax.swing.JLabel;
/**
*
* #author chiyaIDE
*/
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
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">//GEN-BEGIN:initComponents
private void initComponents() {
jButton1 = new javax.swing.JButton();
panel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("button");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, 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()
.addGap(117, 117, 117)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(183, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(jButton1)
.addGap(26, 26, 26)
.addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(80, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
panel.add(new JLabel("Hello"));
panel.revalidate();
System.out.println(i++);
}//GEN-LAST:event_jButton1ActionPerformed
/**
* #param args the command line arguments
*/
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);
}
});
}
public static int i;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JPanel panel;
// End of variables declaration//GEN-END:variables
}
Manual code
public static void paste()
{
frame=new JFrame();
panel=new JPanel();
frame.setSize(400,400);
frame.setVisible(true);
panel.setSize(400,400);
Container cp=frame.getContentPane();
cp.add(panel);
JButton button=new JButton("Click HERE");
panel.add(button);
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
panel.add(new JLabel("Hello"));
panel.revalidate();
}
});
}
Problem is in layout manager. I donĀ“t like netbeans GUI Designers, i prefered make own design, and this is one of many reasons why:
you create some basic GUI with designer. Later you want to add next component into, but it is not "visible" because of layout. Default is "free design" that means GroupLayout. Change it to other appropriate layer or specify position for JLabel.

How to display text in JFrame using Netbeans? How to clear text in a JFrame?

How can I display text in JFrame using Netbeans? And how to clear text in JFrame?
to create a label for text:
JLabel label1 = new JLabel("your text here");
to change the text in the label:
label1.setText("your new text here");
and finally to clear the label:
label1.setText("");
and all you have to to is place the label in your layout, or what ever layout system you are using, and then just add it to the JFrame..
you can use this
#Override
public void paintComponents(Graphics g) {
super.paintComponents(g);
g.drawString("Hello", 0, 0);
}
or use jTextField
jTextField1.setText("Hello");
You can use JLabel to display text, and you can reset by setting its text to "" . check doc
If you're using the Netbeans GUI builder then there's a good beginner's tutorial. Otherwise, if you're coding manually, there's a good guide to Swing on Oracle's site: http://download.oracle.com/javase/tutorial/uiswing/TOC.html
You can create Jlabel.
JLabel l1=new JLabel("Your text");
l1.setText(""); // clear the text
Check Properties.Under the Swing Control you will find the JLabel.Drag & DROP it in your JFRAME.
This code works with Netbeans.. create one new Frame and set Text for you in the middle of the Frame..
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() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Label For The JFrame");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(107, 107, 107)
.addComponent(jLabel1)
.addContainerGap(141, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(88, 88, 88)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(187, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
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.JLabel jLabel1;
// End of variables declaration
}
Replace This jLabel1.setText("Label For The JFrame"); with your customized Label in Code.
and when you want to blank the Label use jLabel1.setText("");
Thanks..

Categories

Resources