I don't understand why the RackBuilder object I added to the frame does not get displayed.
The code runs and the frame gets generated. I expect to see a panel with 42 rows, each row containing a JLabel "test". Is there something incorrect/missing from my constructor?
public class RackBuilderTool extends JPanel{
public RackBuilderTool() {
super(new GridLayout(42, 0));
for (int i = 0; i < 42; i++) {
add(new JLabel("test"));
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Rack Builder Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RackBuilderTool rackBuilder = new RackBuilderTool();
rackBuilder.setOpaque(true);
frame.setContentPane(rackBuilder);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Thanks!
import javax.swing.*;
import java.awt.*;
public class RackBuilderTool extends JPanel{
public RackBuilderTool() {
super(new GridLayout(42, 0));
for (int i = 0; i < 42; i++) {
add(new JLabel("test"));
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Rack Builder Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RackBuilderTool rackBuilder = new RackBuilderTool();
rackBuilder.setOpaque(true);
frame.setContentPane(rackBuilder);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
now it will show you 42 rows of your label.
Realized that the "run" button on Netbeans IDE is to run the entire project. As a result it was running another java file under the same project.
Once I right clicked on the java file I wanted to compile and clicked run it worked.
Thanks everyone for the help.
Related
Whenever I run my code it ends in a few seconds. Why?
This is the Main file:
public class Main {
public static void main(String[] args) {
System.out.println("This is running");
GameWin Win = new GameWin();
}
}
This is the GameWin file:
import java.awt.event.*;
import javax.swing.*;
public class GameWin implements ActionListener{
JFrame frame = new JFrame();
JButton myButton = new JButton("New Window");
public void GameWin(){
myButton.setBounds(100,160,200,40);
myButton.setFocusable(false);
myButton.addActionListener(this);
frame.add(myButton);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420,420);
frame.setLayout(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==myButton) {
frame.dispose();
}
}
}
When I try to run this code it shows running and then the code ends with exit code 1 which is good, but it just ends without showing the window. Is there something wrong with my JRE or JDK?
Constructors do not have return type. public void GameWin() is not a constructor, thus the default constructor is called that does nothing interesting here. It should be declared public GameWin().
You must call any Swing-related function in the Swing-main-thread for consistency. Thus call the construction of the GameWin object through SwingUtilities class. Even if it seems to work without such, it may not in different kind of environnements.
Hence:
import java.awt.event.*;
import javax.swing.*;
public class GameWin implements ActionListener{
public static void main(String[] args) {
System.out.println("This is running");
SwingUtilities.invokeLater(() -> new GameWin());
}
JFrame frame = new JFrame();
JButton myButton = new JButton("New Window");
public GameWin(){
myButton.setBounds(100,160,200,40);
myButton.setFocusable(false);
myButton.addActionListener(this);
frame.getContentPane().add(myButton);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420,420);
frame.setLayout(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==myButton) {
frame.dispose();
}
}
}
In this JTabbedPane screenshot
I am using DnD of Netbeans, and I've been tinkering around it just to put spaces between the tabs. So far I still can't get what I want.
Is there a way to do it?
I'm not sure of another way, but I think you have to install your own customized TabbedPaneUI on your JTabbedPane.
Example:
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class JTabbedPaneWithSpaces implements Runnable
{
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeLater(new JTabbedPaneWithSpaces());
}
public void run()
{
JTabbedPane pane = new JTabbedPane();
pane.setUI(new SpacedTabbedPaneUI());
pane.addTab("One", new JPanel());
pane.addTab("Two", new JPanel());
pane.addTab("Threeeeeee", new JPanel());
pane.addTab("Four", new JPanel());
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.setSize(500, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class SpacedTabbedPaneUI extends BasicTabbedPaneUI
{
#Override
protected LayoutManager createLayoutManager()
{
return new BasicTabbedPaneUI.TabbedPaneLayout()
{
#Override
protected void calculateTabRects(int tabPlacement, int tabCount)
{
final int spacer = 20; // should be non-negative
final int indent = 4;
super.calculateTabRects(tabPlacement,tabCount);
for (int i = 0; i < rects.length; i++)
{
rects[i].x += i * spacer + indent;
}
}
};
}
}
}
I'm building a program that requires swapping out the current, visible JPanel with another. Unfortunately there seems to be multiple to go about this and all of my attempts have ended in failure. I can successfully get the first JPanel to appear in my JFrame, but swapping JPanels results in a blank JFrame.
My Main JFrame:
public class ShellFrame {
static CardLayout cl = new CardLayout(); //handles panel switching
static JFrame frame; //init swing on EDT
static MainMenu mm;
static Panel2 p2;
static Panel3 p3;
public static void main(String[] args) {
initFrame();
}
public static void initFrame() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame = new JFrame();
frame.setDefaultCloseOperation(3);
frame.setLayout(cl);
mm = new MainMenu();
pp = new PlacementPanel();
//first panel added to frame will always show first
frame.add(mm, "MainMenu");
frame.pack(); //sizes frame to fit the panel being shown
frame.setVisible(true);
}
});
}
public static void switchPanel(String name) {
cl.show(frame.getContentPane(), name);
frame.pack();
}
public static void updatePanel2(/* args */) {
frame.removeAll();
p2 = new Panel2(/* args */);
frame.add(pp, "PlacementPanel");
frame.pack();
frame.validate();
frame.repaint();
}
I'm trying to use updatePanel2 to swap out the existing panel with a new Panel2 but It doesn't seem to be working. Panel2 works fine on it's own but trying to use it in conjunction with my program simply yields a blank window. Any help would be greatly appreciated!
that requires swapping out the current, visible JPanel with another
Have a look at CardLayout for a complete example of how to do it properly.
I have a Swing app which 'swaps' Panels when the user press the 'SPACE' key, showing a live plot of a running simulation. What i did goes like this:
public class MainPanel extends JPanel implements Runnable {
// Called when the JPanel is added to the JFrame
public void addNotify() {
super.addNotify();
animator = new ScheduledThreadPoolExecutor(1);
animator.scheduleAtFixedRate(this, 0, 1000L/60L, TimeUnit.MILLISECONDS);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (spacePressed)
plot.render(g);
else
simulation.render(g);
}
public void run() {
simulation.update();
repaint();
}
}
public class PlotView {
public void render(Graphics g) {
//draw the plot here
}
}
public class SimulationView {
public void render(Graphics g) {
//draw simulation here
}
}
This works very well for my 'show live plot' problem. And there's also the CardLayout approach, which you may turn into a new separate question if you having trouble. Good luck!
You should do .setVisible(false); to the panel which you want to be replaced.
Here is a working example, it switches the panels when you press "ENTER";
If you copy this in an IDE, automatically get the imports (shift+o in Eclipse);
public class MyFrame extends JFrame implements KeyListener {
private JButton button = new JButton("Change Panels");
private JPanel panelOnFrame = new JPanel();
private JPanel panel1 = new JPanel();
public MyFrame() {
// adding labels to panels, to distinguish them
panelOnFrame.add(new JLabel("panel on frame"));
panel1.add(new JLabel("panel 1"));
setSize(new Dimension(250,250));
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(button);
add(panelOnFrame);
setVisible(true);
addKeyListener(this);
addKeyListener(this);
setFocusable(true);
}
public static void main(String[] args) {
MyFrame frame = new MyFrame();
}
#Override
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_ENTER){
//+-------------here is the replacement:
panelOnFrame.setVisible(false);
this.add(panel1);
}
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
public class WASD extends JFrame{
Ellipse2D.Double ball;
int ballx = 100;
int bally = 100;
static JTextField typingArea;
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
WASD frame = new WASD("frame");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.addComponentsToPane();
frame.pack();
frame.setVisible(true);
}
private void addComponentsToPane(){
typingArea = new JTextField(20);
//typingArea.addKeyListener(this);
}
public WASD(String name){
super(name);
}
}
When I run the program all I get is an empty window. The JTextField doesn't show up. Thanks!
(Apparently my post has too much code, so I'm adding this to make it let me submit. Ignore this sentence and the previous one.)
The JTextField needs to also be added to the frame after it is created.
private void addComponentsToPane(){
typingArea = new JTextField(20);
frame.add(typingArea);
}
--EDIT--
I have got a welcome window consisting of two JLabels. It has a link to a timer counting from 3 to 0. After that time, a new window, "UsedBefore", containing JLabel and radio buttons should automatically appear in the place of the previous one. When I run the "Launcher", the first window shows up with counter displaying 3,2,1,0 and then nothing happens.
I think the problem lies in poor referencing, but I'm not sure. I've got "Launcher" class:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
Welcome window = new Welcome();
window.setVisible(true);
}
});
} // end main
Where I launch the "Welcome" window:
public Welcome() {
init();
}
public void init() {
// here I'm adding stuff to the window and then I have:
setLayout(cardLayout);
add(big, "1welcome");
// UsedBefore.MakeUsedBeforeWindow(); // ???
new MyTimer(this).start();
} // end init
this goes to MyTimer which does the countdown and:
welcome.showNextWindow(); // private Welcome welcome;
we go back to the "Welcome" class:
public void showNextWindow() {
cardLayout.next(this);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("My Frame");
frame.getContentPane().add(new Welcome());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(550, 450);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
and finally the "UsedBefore" class:
public UsedBefore() {
super(new BorderLayout());
init();
}
public void MakeUsedBeforeWindow() {
String q = "Have you used GUI before?";
JPanel area = new JPanel(new BorderLayout());
add(area, "2usedBefore?");
area.setBackground(Color.white);
JLabel textLabel = new JLabel("<html><div style=\"text-align: center;\">"
+ q + "</html>", SwingConstants.CENTER);
textLabel.setForeground(Color.green);
Font font = new Font("SansSerif", Font.PLAIN, 30);
textLabel.setFont(font);
textLabel.setBorder(new EmptyBorder(0, 0, 250, 0)); //top, left, bottom, right
area.add(textLabel, SwingConstants.CENTER);
add(area, "2usedBefore?");
}
with its main:
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("RadioButtons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane - not sure how to do it
// JComponent newContentPane = new UsedBefore();
// newContentPane.setOpaque(true); //content panes must be opaque
// frame.setContentPane(newContentPane);
// frame.getContentPane().add(new UsedBefore());
//Display the window.
frame.setSize(550, 450);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
That's quite a journey. Sorry for a lot of code, I hope the path is clear. Once I've got 1->2->3 links right, I should be able to do the rest of them, so any help is appreciated. Thank you.
I suggest a slightly different approach. Why not building JPanel instead of Windows and adding/removing these JPanel at the desire time.
Ex (here welcome panel is shown first with its decreasing counter and when the counter reach 0, other panel is shown):
public class T extends JFrame {
private int couterValue = 3;
private JPanel welcome;
private JLabel counter;
private JPanel other;
private Timer timer;
public T() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
buildWelcomePanel();
buildOtherPanel();
add(welcome);
setSize(550, 450);
setLocationRelativeTo(null);
setVisible(true);
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (couterValue == 0) {
timer.cancel();
// Switch the panels as the counter reached 0
remove(welcome);
add(other);
validate();
} else {
counter.setText(couterValue + ""); // Update the UI counter
couterValue--;
}
}
}, 0, 1000);
}
private void buildWelcomePanel() {
welcome = new JPanel();
counter = new JLabel();
welcome.add(counter);
}
private void buildOtherPanel() {
other = new JPanel();
JLabel otherStuff = new JLabel("Anything else ...");
other.add(otherStuff);
}
public static void main(String[] args) {
new T();
}
}