I am trying to connect a TV to the Laptop. I want to display one JFrame on Laptop and another on my TV. But my code only recognises the Laptop monitor. It does not seem to recognise the TV as a second monitor.
I am experiment with this code:
public static void disponscreen() {
System.out.println("Hello from the Disp on screen Function!");
Integer j=0;
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
System.out.println("No of monitord"+ge.getDefaultScreenDevice());
System.out.println("No of monitord"+gs.length);
GraphicsDevice gd = gs[0];
GraphicsConfiguration[] gc = gd.getConfigurations();
JFrame f = new JFrame("simple gui");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel("I'm a label in the window");
textLabel.setPreferredSize(new Dimension(300, 100));
f.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window. frame.setLocationRelativeTo(null); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { createWindow(); } }
f.setVisible(true);
}
public static void main(String[] args) {
System.out.println("Hello from the Java Main Function!");
disponscreen();
}
gs.length is 1 regardless of connecting or not connecting a TV
I expect to have gs.length = 2.
Related
I want to make a FadeTransition within a pane in my application. Also, with this FadeTransition I set the visibitilitys of some JavaFX inside the pane to false, to make them disappear. It's working fine but, when I call another method that I named waitForResponse(event) after the FadeTransition it just stops working. I don't know why.
If I comment the waitForResponse(event) the FadeTransitions start working again.
I've thought that maybe it's a problem with the Socket and the InputStreamReader inside the waitForResponse(event), but I tested taking it out and making another basic thing inside this method still not work.
I've made other tests and dicovered that FadeTransition and other visibility changes doesn't work if I put any bufferedReader, other loops ou decision structures after it.
I just want to make a loading screen that prevent user to click anywhere until it's finished.
This is the code:
public class LoadingScreenController implements Initializable {
// Socket que vai ser utilizado nos vários métodos para conversar com o servidor
private Socket cliente;
// PrintWriter que vai ser utilizado pelos vários métodos e vai passar o
// argumento para o switch case
private PrintWriter pr;
private InputStreamReader in;
private BufferedReader bf;
private String option;
private String response;
#FXML
private Button refreshButton;
#FXML
private ImageView loadingGif;
#FXML
private Label txtLabel;
#FXML
private AnchorPane rootPane;
public String getOption() {
return option;
}
public void setOption(String option) {
this.option = option;
}
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
private void makeFadeInTransition() {
FadeTransition fadeTransition = new FadeTransition(Duration.seconds(1), loadingGif);
fadeTransition.setFromValue(0.0);
fadeTransition.setToValue(1.0);
fadeTransition.play();
}
#FXML
private void onRefreshButtonAction(ActionEvent event) {
if (option == null) {
throw new IllegalStateException("Entity was null");
}
refreshButton.setVisible(false);
refreshButton.setDisable(true);
txtLabel.setVisible(false);
makeFadeInTransition();
sendOptionToServer(event);
}
#FXML
private void sendOptionToServer(ActionEvent event) {
try {
cliente = new Socket("localhost", 3322);
pr = new PrintWriter(cliente.getOutputStream());
in = new InputStreamReader(cliente.getInputStream());
bf = new BufferedReader(in);
pr.println(option);
pr.flush();
waitForReponse(event, bf);
} catch (IOException e) {
e.printStackTrace();
}
}
private void waitForReponse(ActionEvent event, BufferedReader bf) throws IOException {
response = bf.readLine();
switch (response) {
case "a":
Utils.currentStage(event).close();
break;
}
}
}
Your sendOptionToServer(...) method, and in particular your waitForResponse(...) method, contains blocking calls that block execution until they are complete (i.e. until you receive a response from the server). Since you're running these on the FX Application Thread, you prevent that thread from doing its normal work until those calls complete. This means it won't update the UI or process any user events until you have received and processed the response from the server.
You should place the calls to blocking methods in a background thread to allow the FX Application Thread to proceed in the meantime. The javafx.concurrent API makes this reasonably easy to do; here a Task should suffice.
Here's a version that uses a Task. I also used a "try with resources" to ensure everything that needs to be closed is correctly closed.
#FXML
private void sendOptionToServer(ActionEvent event) {
Task<String> serverCommunicationTask = new Task<>() {
#Override
protected String call() throws Exception {
try (
Socket cliente = new Socket("localhost", 3322);
PrintWriter pr = new PrintWriter(cliente.getOutputStream());
BufferedReader bf = new BufferedReader(new InputStreamReader(cliente.getInputStream()));
) {
pr.println(option);
pr.flush();
return bf.readLine();
}
}
};
serverCommunicationTask.setOnSucceeded(event -> {
if ("a".equals(serverCommunicationTask.getValue())) {
rootPane.getScene().getWindow().hide();
}
});
serverCommunicationTask.setOnFailed(event -> {
event.getException().printStackTrace();
// handle exception...
});
Thread thread = new Thread(serverCommunicationTask);
thread.setDaemon(true);
thread.start();
}
For a project of mine (I'm very new & even newer to guis) I'm making a GUI based game it has worked so far however, when you complete level one, it reopens level two but the JFrame is completely white and unresponsive, I have tried a few things but however I am not close to finding out what the issue is. Please help me, The code for the game is:
public class gameWithGuis extends JFrame implements ActionListener, Runnable{
static int levelNum = 1;
static int find;
static int length = 3;
static int area = length * length;
static ArrayList<JButton> buttonsHolder = new ArrayList<JButton>();
Container pane = getContentPane();
static gameWithGuis threadA = new gameWithGuis(); //Starts 10 second timer
static Thread timerThread = new Thread(threadA);
static boolean levelUp = false;
public void run(){
try{
int time = 1;
while (time<=10){
Thread.sleep(1000);
time++;
}
super.dispose();
JOptionPane.showMessageDialog(null,"You have ran out of time! Game over!");
highscores(levelNum);
}catch (Exception e){}
}
public void main(){
Scanner sc = new Scanner(System.in);
JOptionPane.showMessageDialog(null,"Welcome to pseudo-Where's Wally, look for the lower case L(l) character.");
JOptionPane.showMessageDialog(null,"You get 10 seconds to find it.");
JOptionPane.showMessageDialog(null,"The answer are the coordinates multiplied together.");
JOptionPane.showMessageDialog(null,"That is what you must type in. Good luck!");
JOptionPane.showMessageDialog(null,"Ready?..");
char clear = (char)(12);
System.out.print(clear);
timerThread.start();
makingGrid();
}
public static void highscores(int levelNum){
AQAWriteTextFile2013 writer = new AQAWriteTextFile2013();
AQAReadTextFile2013 reader = new AQAReadTextFile2013();
Scanner scTwo = new Scanner(System.in);
String fileName = "highscores.txt";
String save = JOptionPane.showInputDialog(null,"Would you like to save your score? (yes or no): ");
if (save.equalsIgnoreCase("yes")){
String runningLine = "";
String name = JOptionPane.showInputDialog(null,"Name please: ");
writer.openFile(fileName, true); //opens highscore file
String writeLine = name + "\t" + levelNum;
writer.writeToTextFile(writeLine); //writes your name and the level you reached to the file
writer.closeFile();
reader.openTextFile(fileName); //shows you the list of peoples scores
JOptionPane.showMessageDialog(null,"Current Highscores: ");
String line = reader.readLine();
if (line ==null) JOptionPane.showMessageDialog(null,"- - NONE - -"); //if file is empty
do //prints the lines within the file
{
line = reader.readLine();
runningLine = runningLine+"\n"+line+" ";
}while (line !=null);
JOptionPane.showMessageDialog(null,runningLine);
reader.closeFile();
System.exit(0);
} else if (save.equalsIgnoreCase("no")){
JOptionPane.showMessageDialog(null,"Okay, thank you for playing!");
System.exit(0);
} else {
JOptionPane.showMessageDialog(null,"Please answer yes or no."); //validation
}
}
public static void main(String[] args) throws Exception{
new gameWithGuis().main();
}
#Override
public void actionPerformed(ActionEvent arg0){
JButton[] buttons = buttonsHolder.toArray(new JButton[buttonsHolder.size()]);
// for(int i = 0; i<=amountOfButtons; i++){
// buttonsHolder[].toArray();
// // buttons[i] = buttonsHolder[i];
// }
if(arg0.getSource().equals(buttons[find])){
timerThread.stop();
JOptionPane.showMessageDialog(null,"Correct!");
levelNum++;
JOptionPane.showMessageDialog(null,"Level up! You are now on level: "+levelNum+". The grid has an area of "+(length*length)+" now.");
levelUp = true; //go through to the next level
pane.removeAll();
super.dispose();
makingGrid();
}else{
timerThread.stop();
JOptionPane.showMessageDialog(null,"You guessed wrong! Game over!");
JOptionPane.showMessageDialog(null,"You reached level: "+levelNum+".");
highscores(levelNum);
}
}
public void makingGrid(){
do{
if(levelNum>1){
length = length + 2; //increase length and height of box by 2 both ways
area = length*length;
}
JButton[] buttons = new JButton[area];
Random gen = new Random();
find = gen.nextInt(area);
setTitle("Where's J?");
// Container pane = getContentPane();
pane.setLayout(new GridLayout(length, length));
for(int i = 0; i<area; i++){
buttons[i] = new JButton();
buttons[i].setText("I");
if(i == find){
buttons[i].setText("J");
}
buttonsHolder.add(buttons[i]);
pane.add(buttons[i]);
buttons[i].addActionListener(this);
}
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// timerThread.start();
} while (levelUp);
}
}
Please no sarcastic comments if I'm being stupid and missed something obvious too you, I'm new too this language and to this website. Thanks for any help.
don't worry... No one will give you a sarcastic comment. It is just not right or fair.
Your code has a lot to improve. But congratulations for writing it!
Your problem is that levelUp is always true on the second level. This causes an infinite loop inside the makingGrid(). In this case JFrame stop repainting.
I've just started to use the Eclipse Window Builder plugin to create a JFrame for my program but when adding a JTable it's just not showing up. The program acts like it's there but won't show it.
public class Stock extends JFrame {
private static final long serialVersionUID = -4904110593143929972L;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Stock frame = new Stock();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Stock() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("Add");
menuBar.add(mnNewMenu);
JMenu mnNewMenu_1 = new JMenu("Delete");
menuBar.add(mnNewMenu_1);
JMenu mnNewMenu_2 = new JMenu("Edit");
menuBar.add(mnNewMenu_2);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table = new JTable();
table.setBounds(10, 230, 414, -221);
contentPane.add(table);
loadTable();
}
public void loadTable() {
String[] columnNames = {"Key",
"Name",
"Quantity",
"Price per unit"};
Object[][] data = {
{"1","Name","10","�2.40"}};
table = new JTable(data, columnNames);
contentPane.add(table);
}
}
Like I said, I've only just started with Window Builder so it's probably just simple but I can't figure it out.
Sorry the issue was this line, "
contentPane.setLayout(null);" no idea how it got there. Ah well least its working :)
When running the JAVA app in Eclipse, the JFrame title is displayed, but when running the exported JAR file, there is no title showing on the frame.
public void mouseMoved(MouseEvent e) {
f.setTitle("X: " + location.x + " , Y: " + location.y);
recenterMouse();
}
public void init() {
// add frame
f = new JFrame("Muis Meet");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(screensizex, screensizey);
f.getContentPane().add(this, FlowLayout.LEFT);
f.setVisible(true);
centerLocation.x = getWidth() / 2;
centerLocation.y = getHeight() / 2;
recenterMouse();
addMouseListener(this);
addMouseMotionListener(this);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MuisMeet muismeet = new MuisMeet();
muismeet.init();
}});
}
#Override
public void mousePressed(MouseEvent arg0) {
recenterMouse();
location.x = 0;
location.y = 0;
f.setTitle("X: 0 , Y: 0");
}
}
Found the problem. In the Export dialog box, another project was automatically selected under Launch Configuration - not the project I right-clicked upon.
Following the is the code I have for listening to messages from Windows form.
I have noticed that when I click on send it sends a message to MyQueue but at that time I was hoping the event mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e) should get called but it is not, in other words I am trying to subscribe to MyQueue from Windows form. Just wondering if I am missing something in the code:
public class Form1 : System.Windows.Forms.Form
{
public System.Messaging.MessageQueue mq;
public static Int32 j=0;
public Form1()
{
// Required for Windows Form Designer support
InitializeComponent();
// Queue Creation
if(MessageQueue.Exists(#".\Private$\MyQueue"))
mq = new System.Messaging.MessageQueue(#".\Private$\MyQueue");
else
mq = MessageQueue.Create(#".\Private$\MyQueue");
mq.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompleted);
mq.BeginReceive();
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnMsg_Click(object sender, System.EventArgs e)
{
// SendMessage(Handle, 1, 0, IntPtr.Zero);
System.Messaging.Message mm = new System.Messaging.Message();
mm.Body = txtMsg.Text;
mm.Label = "Msg" + j.ToString();
j++;
mq.Send(mm);
}
void mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
//throw new NotImplementedException();
}
private void btnRcv_Click(object sender, System.EventArgs e)
{
System.Messaging.Message mes;
string m;
try
{
mes = mq.Receive(new TimeSpan(0, 0, 3));
mes.Formatter = new XmlMessageFormatter(new String[] {"System.String,mscorlib"});
m = mes.Body.ToString();
}
catch
{
m = "No Message";
}
MsgBox.Items.Add(m.ToString());
}
}
See MSDN's example on how to use the ReceiveCompletedEventHandler .
They have a console app where the Main() does the same as your Form1(), but your handler doesn't have any code. You've said it doesn't call back into your event delegate, but perhaps check your queue name is correct on the constructor.
Consider using MSDN's sample code in a new console app to test your environment first, then go back to your WinForms code with any lessons learned.
private static void MyReceiveCompleted(Object source,
ReceiveCompletedEventArgs asyncResult)
{
MessageQueue mq = (MessageQueue)source;
Message m = mq.EndReceive(asyncResult.AsyncResult);
Console.WriteLine("Message: " + (string)m.Body);
mq.BeginReceive();
return;
}
If you want to inspect the queue and get a message on the click of a button, you can simply move the statement mq.BeginReceive(); to the btnRcv_Click() in place of .Receive();